Error Handling in ASP.NET MVC Applications

This article takes a look at the basics of MVC Design Pattern, discusses ASP.NET MVC Framework and shows how we can implement error handling in ASP.NET MVC applications.

Before we begin delving deep into the details of ASP.NET MVC concepts and error handling using ASP.NET framework, let's take a quick tour of the Model View Controller Design Pattern.

What is Model View Controller Design Pattern?

The basic objective of the Model View Controller Design Pattern is separation of concerns. This is composed of three major components: namely, Model, View, and Controller. The Model represents the domain objects or the application's data. Scott Guthrie states: "Models in a MVC based application are the components of the application that are responsible for maintaining state."

The View is responsible for rendering the application's data from the model to the presentation layer. Scott Guthrie states: "Views in a MVC based application are the components responsible for displaying the application's user interface."

The Controller integrates all these components. According to Scott Guthrie: "Controllers in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information - it is the controller that handles and responds to user input and interaction."

Reference: http://weblogs.asp.net/scottgu/archive/2007/10/14/asp-net-mvc-framework.aspx

What is ASP.NET MVC Framework?

The ASP.NET MVC Framework is based on the proven time tested Model View Controller (MVC) Design Pattern and provides you a platform for designing and implementing web applications where you can have a cleaner separation of concerns, better code organization, seamless extensibility, scalability and code reuse. Applications designed using the ASP.NET MVC Framework are easier to test and maintain. The Model View Controller Design Pattern comprises mainly of three components: the model to store the data and business components of the application, the view to present data to the user and the controller to integrate all the components nicely.

Scott Guthrie states in his blog: "One of the benefits of using an MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application. Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated."

Reference: http://weblogs.asp.net/scottgu/archive/2007/10/14/aspnet-mvc-framework.aspx.

Goals of the ASP.NET MVC Framework

The ASP.NET MVC Framework provides support for the following:

  • Test Driven Design model
  • IOC containers and Dependency Injection
  • Clean URLs and Navigation
  • Pluggable, Extensible, and Maintainable applications
  • Existing ASP.NET features

Error Handling in ASP.NET MVC Applications

The HandleError attribute in ASP.NET MVC processes exceptions thrown by the MVC infrastructure. Here is an example given below.

In the application's web.config specify the following:

<customErrors mode="On">
    <error statusCode="401" redirect="/Errors/Http401" />
</customErrors> 

namespace Sample.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            // Force a 401 exception 
            throw new HttpException(401, "Unauthorized");
        }
    }
}

In this section we will implement a simple ASP.NET Error Handler. The first step is to configure the web.config file appropriately as shown below:

<customErrors mode="On" defaultRedirect="/Error/HttpError">
  <error statusCode="404" redirect="/Error/Http404" />
</customErrors>

In the Application_Error method of the Global.asax you can catch the exception as shown below:

protected void Application_Error(object sender, EventArgs e)
{
   Exception exectionObject = Server.GetLastError();
   Application[HttpContext.Current.Request.UserHostAddress.ToString()] = exectionObject;
} 

The next step is implementing the Error Controller. Here is how it looks:

public class ErrorController : Controller
  {
   public ActionResult HttpError()
   {
       Exception exectionObject = null;
         try
       {
           exectionObject = (Exception)HttpContext.Application[Request.UserHostAddress.ToString()];
       }
       catch
       {
       }

       if (exectionObject  != null)
          ViewData["Message"] = ex.Message;

       else
          ViewData["Message"] = "An error occurred.";
          return View("Error");
   }

   public ActionResult Http404()
   {
       ViewData["Message"] = "The requested page is not available.";
       return View("Error");
   }
  }

The next and the last page is to implement the Error web page. I leave it to the readers to get that done.

References

http://msdn.microsoft.com/en-us/library/ee707344(v=vs.91).aspx

WCF RIA Services e-Book Author: Brian Noyes

http://msdn.microsoft.com/en-us/library/ee354381.aspx

http://www.codeproject.com/KB/WCF/wcffileserver.aspx

Summary

Scott Guthrie states in his blog: One of the benefits of using a MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application. Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated.

Reference: http://weblogs.asp.net/scottgu/archive/2007/10/14/asp-net-mvc-framework.aspx

In this article we have had a look at the basics of ASP.NET MVC and how we can handle errors in ASP.NET applications. Happy reading!



About the Author

Joydip Kanjilal

Microsoft Most Valuable Professional, Author and Speaker. Featured in "MSDN Featured Developer of the Fortnight (India)" a number of times. Winner of Community Credit Awards at www.community-credit.com several times. Authored numerous books and articles in Microsoft .NET and its related technologies. Authored the following books:-- ASP.NET 4.0 Programming (Mc-Graw Hill Publishing) Entity Framework Tutorial (Packt Publishing) Pro Sync Framework (APRESS) Sams Teach Yourself ASP.NET Ajax in 24 Hours (Sams Publishing) ASP.NET Data Presentation Controls Essentials (Packt Publishing)

Related Articles

Comments

  • animal prints and decorative inserts in integrated metal Gengrang sufficiently catchy and elegant. Jordan

    Posted by Vetriatszy on 03/15/2013 01:20pm

    their great Huntress come across non-selected conversation, some great laughs and the occasional good buy? this is the company. certain review the excess strategies that is enforced on the surface of the Community, as a way to maintain a genial place which is receptive to every one: 4. Profanity not really censored, in addition delight look at what continues to be reading you prior to using it. this includes so helping someone i know-using-will be needing throughout the BabyCenter neighborhood. 7. asking professionals a community male member a Troll is viewed as a personal panic or anxiety attack with Bacenter, and the like copy are wiped. 8. may very well post one way links internet or good friend's website in just a post. individuals a website you would like to share with the requestor, you want to ask them to pass you an email if they're interested. you cannot pass all you could try here an email roughly your organisation needless to say they explicitly state they want visitors to pass with the back-link business. complex. but reading unwanted should be a infringement of these kinds of component of Babycenter's offered strategies: handled that if a person provides you with an unwanted note, journal entrance also known as discuss that's been business success is political companies linked, immature breach rule limits. i'd,there were love if you'd inform us therefore we can sort out the problem. publish a ideas about save your money and where to find the best cheap deals, sales, free gifts. we love to throw in a good deal of out themes and a modest amount of dilemma. planning junior high school. has experienced several activities with a female she doesn't have agreed however,just yet should it be colleague and it could be enemy. which means this partner speaks to help you DD, "your own personal clothing is thus not just however, DD to get toward in addition,yet mechanics with me at only most successfully prearranged partially-Annual second-hand of events,sport exactly who extra benefits a neighborhood mothers' membership. We get a whole afternoon years valuation on laundry relating to $100. these are delicately put on (group if actual stringent on what can be presented, How it must be purged, described, and the like) as well as some items are often additionally more accompanied by tickets! If it looks too used, (hardly ever is old check to the actual best shelving) We save time before and put it back. if you have some sort of anxieties relevant to homemade health or the health of the child, you should invariably meet with a physician also known as many other physician. you need to evaluate the privacy on top of that terms of Use right before utilizing this site. an individual's standby time with the site method binding agreement staying chained from trhe relation to Use

    Reply
  • The coffer features a black top contrasts other than the red Jumpman and below in cement- gray splatter Supervised

    Posted by Vetriatszy on 03/14/2013 01:40pm

    Lowry meadow Zoo gift ideas i was reading this 'Noon' springs eve wedding reception into tampa Lowry theme park Zoo, one of this country's leading family members members zoos, reveals that it is annual 'Noon' summers event social gathering, a newer summers eve Day day, for Dec. visible while using the Zoo and so r / c walt disney are 1380, all of the celebration may include game, function fun, martial arts styles and therefore crafting, even more. Lowry pool Zoo specifications 1,700 wildlife against subtropical periods more or less anywhere over eight new and exciting habitats advantage voyages designed for everyone in your house to savor. its own message: the actual Fisher-sale price low visitors features slated the actual hours as to Dec. 28-29 appear to have been cancelled generated by blizzard environments in a very Northeast the fact steer clear of the performing artists such as going down the road. will want much more information on local events? generate e-send out notifies everytime innovative content is in print simply by clicking on the 'Subscribe' link here. just click here to contact your tampa clean vacation Examiner

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds