Exception or Error Handling in ASP.Net MVC Using HandleError Attribute

Introduction

Exception handling may be required in any application, whether it is a web application or a Windows Forms application.

ASP.Net MVC has an attribute called "HandleError" that provides built-in exception filters. The HandleError attribute in ASP.NET MVC can be applied over the action method as well as Controller or at the global level. The HandleError attribute is the default implementation of IExceptionFilter. When we create a MVC application, the HandleError attribute is added within the Global.asax.cs file and registered in the Application_Start event.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());

}

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

}


Important properties of HandleError attribute

The HandleError Error attribute has a couple for properties that are very useful in handling the exception.

ExceptionType: Type of exception to be catch. If this property is not specified then the HandleError filter handles all exceptions.

View: Name of the view page for displaying the exception information.

Master: Master View for displaying the exception.

Order: Order in which the action filters are executed. The Order property has an integer value and it specifies the priority from 1 to any positive integer value. 1 means highest priority and the greater the value of the integer is, the lower is the priority of the filter.

AllowMultiple: It indicates whether more than one instance of the error filter attribute can be specified.

Example

[HandleError(View = "Error")]
public
class HomeController : Controller
{
    public ActionResult Index()
    {

        ViewBag.Message = "Welcome to ASP.NET MVC!";

        int u = Convert.ToInt32("");// Error line

        return View();

    }

}

HandleError Attribute at Action Method Level

 

[HandleError(View = "Error")]
public
ActionResult Index()
{

    ViewBag.Message = "Welcome to ASP.NET MVC!";

    int u = Convert.ToInt32("");// Error line

    return View();

}

Defining HandleError Attribute at Global Level

We can also apply the HandleError Attribute at the global level by registering it in the Global.asax in Application_Start event.

Example

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute(), 2); //by default added


    filters.Add(new HandleErrorAttribute

    {

        View = "Error"

    }, 1);

}

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);

    RegisterRoutes(RouteTable.Routes);
}

Error Page

@model System.Web.Mvc.HandleErrorInfo
@{

    ViewBag.Title = "Error";

}

<
h2>
    Sorry, an error occurred while processing your request.
    <br />

    Error :

</
h2>
<
p>
     @Model.Exception

</
p>

Enabling Custom Error Handling

To enable custom error handling in the application by the HandleError attribute, we must add a CustomErrors element within the system.web section of web config.

<system.web>
  <
customErrors mode="On" defaultRedirect="Error" />
   ….

   …..
<
system.web>


Output

Catch Specific Type of Error

The ExceptionType property can help us to catch a specific type of error. For example, if we want to catch only an ApplicationException type of exception then we can define the ExceptionType.

[HandleError(ExceptionType = typeof(ApplicationException), View = "Error")]
public
ActionResult Index()
{

    ViewBag.Message = "Welcome to ASP.NET MVC!";

    int u = Convert.ToInt32(""); // Error line
    return View();

}


Limitation of HandleError attribute

  • It does not catch a HTTP exception other than 500 and bypasses all the others.
  • It is not able to catch an exception raised outside of controllers.
  • The logging of an exception is not supported by the HandleError attribute.
  • It returns an error view even if the error occurred in an AJAX client call.

Summary

The HandleError exception Filter can be applied over the action method or on the controller even if at the global level. An Exception Filter is implemented from the IExceptionFilter interface and it calls the OnException method when the exception occurs. Finally, using this attribute, we can handle exceptions with some limitations.

Up Next
    Ebook Download
    View all
    Learn
    View all