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

  • There are no comments yet. Be the first to comment!

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