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."


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."


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" />

namespace Sample.Controllers
    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" />

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;
           exectionObject = (Exception)HttpContext.Application[Request.UserHostAddress.ToString()];

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

          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.


WCF RIA Services e-Book Author: Brian Noyes


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.


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 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


  • 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

  • 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

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

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date