Click here to Skip to main content
15,886,110 members
Articles / Web Development / ASP.NET
Article

MVC Application - Part 2 - Error Display

Rate me:
Please Sign up or sign in to vote.
2.50/5 (3 votes)
6 Jul 2010CPOL4 min read 27.4K   8   2
An application to demonstrate MVC error display.

Introduction - Part 2 - Error Display

This is part 2 in a several part article to show how MVC can be used to write an application. Part 1 shows the usage of creating an EntityFramework database, a controller, a view, and some validation. Part 2 shows error displays. Over the course of a few articles, we will write an application showing multiple areas of what MVC can do and various features in MVC.

Background

I started to do this since MVC was new and I wanted to learn it since I know this will be a great technology. All you should need to know is some C#, and as I get into some of the technology, other MVC articles will help. I will not get into what is a controller and a view at this time since there are plenty of articles that do a great job on describing that.

Using the Code

When errors occur, we want to display our error pages and not the standard yellow screen like this one:

unhandled screen

I did a search in trying to find a good way to handle errors, and found a good URL that hosted what I wanted so most of this is due to this site. The file "HandleErrorWithMINOAttribute.cs" in the helper directory is a stripped down version of that.

C#
public override void OnException(ExceptionContext context)
{
    // 
    // Invoke the base implementation first.
    // This should mark context.ExceptionHandled = true 
    // which stops ASP.NET from producing
    // a "yellow screen of death." This also sets the 
    // Http StatusCode to 500 (internal server error.)
    //
    // Assuming Custom Errors aren't off,
    // the base implementation will trigger the application 
    // to ultimately render the "Error" view from one of the following locations:
    //
    //      1. ~/Views/Controller/Error.aspx
    //      2. ~/Views/Controller/Error.ascx
    //      3. ~/Views/Shared/Error.aspx
    //      4. ~/Views/Shared/Error.ascx
    // 
    // "Error" is the default view, however,
    // a specific view may be provided as an Attribute property.
    // A notable point is the Custom Errors
    // defaultRedirect is not considered in the redirection plan.
    //
    base.OnException(context);

    var e = context.Exception;
    LogException(e);
}

I added a "LogException" to the code so we can see the errors that happen. Before each controller method that we want to call, we will add this attribute to it. We also want to tell the error what view to go to when the error happens. We can do this by specifying the view in the attribute. You can see this in the code snippet below.

C#
[HandleErrorWithMINO(ExceptionType = typeof(System.Data.UpdateException), 
 View = "UpdateError")]
[HandleErrorWithMINO(ExceptionType = typeof(System.Data.ConstraintException), 
 View = "ConstraintError")]
public ActionResult Create([Bind(Exclude = "Emp_Id")]Employee empins)

What the code above will do is when an error of type System.Data.UpdateException occurs, the view UpdateError will be called. The attribute with no ExceptionType will call the default view, which we will set in the web.config. The sequence of trials will be what is documented above. The controller directory will be looked at first to see if the view is there, then the shared directory will be searched. Now, remember that these are unhandled exceptions. So if you handle them, the default view will not be shown. You must then show the view you want the user to see.

Now if you want to catch an error and then based on some logic call a specific view, you can call it specifically. One recommendation is to have your own error codes and then throw what you need when you need to. The example below demonstrates this using a standard exception.

C#
// for showing purpose trigger a specific view 
if (Emp_Ins_toEdit.Emp_City != "Boston")
{
    throw new System.Data.ConstraintException("Not Boston");
    return View("");
}

Now to actually see the error views, you have to enable them. This has caught me several times where I add the views and never see them. These are called custom views. They are not enabled by default; to see them, you must add the following to the web.config file. I put this right after the "system.web" section so it is easy to see and change.

XML
<customErrors mode="On" defaultRedirect="ErrorPage.htm" >
  <error statusCode="404" redirect="404filenotfound.htm" />
</customErrors>

What the section does is tell the system that custom errors are enabled and the default redirect is now to a page called "ErrorPage.htm". You can also add many additional lines that will redirect for each specific error, such as a 404 or another error. In the example, when the application has an error 404, it will be redirected to a page called "404filenotfound.htm". A key piece about the default redirect is that it is based where the web.confg is at. If you put the file in another directory, you have to base it off of that.

At this point, you should be able to trigger an error such as adding an employee that has the same first, middle, and last name, that will trigger an error. This should give an UpdateException and display UpdateError.aspx. You should see the following page:

handled screen

Points of Interest

Not showing the standard yellow screen is very important. You need to be able to show the user a much better error display that they and customer support can understand. Also, being able to log errors to a file so you can read it later is very important so that you can see a sequence of errors that occurred. If you want to use an Open Source solution instead of writing your own, I would highly recommend elmah since my article is based off of it. I wrote this instead of using elmah only so I could learn about the error system. I will probably use elmah later as I get the application further along; for now, I wanted to learn.

History

  • 28 June 2010 - Initial release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
I am a Director of Engineering, have an MBA and work in C# forms, Asp.Net and vb.net. I have been writing Windows program since windows 3.0. I am currently working in the Healthcare industry.

I enjoy reading, music (most types), and learning new technology. I am involved in opensource projects at codeplex.

My linkedin link is
http://www.linkedin.com/in/donsweitzer

Comments and Discussions

 
GeneralMy vote of 2 Pin
mnewboult26-Jul-12 3:43
mnewboult26-Jul-12 3:43 
GeneralMy vote of 2 Pin
Not Active6-Jul-10 2:43
mentorNot Active6-Jul-10 2:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.