Handling Exception using HandleError Attribute in Asp.Net MVC

Today we will see how to handle the exception in ASP.NET MVC using HandleError attribute. In ASP.NET MVC, there are different ways to handle the exception. Generally we can use Try-Catch or HandleError Attribute  or we use web.config to show the relevant page when exception occurs.

We can use [HandleError] attribute with your action to handle the exception at action level or at controller level and also at global level.

public ActionResult Index()
public class BasicController : Controller

To use [HandleError] attribute we need to decorate the action with this attribute, means it will be applied to that action only.

It is a two step proccess next we need to add custom errors in web.config.

<customErrors mode="On" ></customErrors>

The HandleErrorfilter handles the exceptions that are raised by the MVC controller actions, filters and views, by default it returns a custom view named Error which is placed in the Sharedfolder. The HandleErrorfilter will works if we have enabled <customErrors> section  in web.config.


And also we can add some other details like type of the exception and error View name, so that when type of exception occurs that error view will be displayed.

[HandleError(ExceptionType = typeof(NullReferenceException), View = "Error")]
        public ActionResult TestProfile()
            UserContext dbContext = new UserContext();
            var testProfile = (from profile in dbContext.UserProfile
                           where profile.FirstName == "abc"
                           select profile);

            string Address = testProfile.FirstOrDefault().Address;
            return View();

You can also add different views for different types of the exception as in the following to decorate multiple HandleError attribute.

[HandleError(ExceptionType= typeof(DivideByZeroException), View= "GeneralError")]
    [HandleError(ExceptionType = typeof(DataException), View = "DBError")]
    public class HomeController : Controller

Implementing HandleError at global level

Also to handle error at global level or for entire application and show the custom error page or view we need to add the HandleError filter with RegisterGlobalFilters() inside the FilterConfig.cs.

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

Note: here you can add your custom filter into the global filter collection where you can define the type of the exception and view needs to be shown which I have explained in another article about CustomErrorHandler.

The exception filters are attributes that can be applied over an action or a controller or even at a global level. When you apply the filter at the global level then it will handle the exceptions raised by all the actions and all the controllers. The exception filters not only catches the exceptions that are raised by the actions but also the ones that are raised by the action filters that are applied over the actions in MVC.

Limitations of the HandleError Attribute:
1. It does not log the error we have to do it manually.
2. It handles the error coming in the MVC context - controllers/ action & views.
3. It only handles HTTP 500 status error, if any other HTTP code error generates then it will not handle by HandleError attribute.
4. It returns only view while making the ajax call which is not correct.

customErrors in web.config
The "customErrors" setting in the web.config allows to define custom error pages for specific HTTP error codes.

All MVC exception handling techniques do not handle HTTP errors like 404 file not found, HTTP 500 error etc. For that we need to make an entry in the config file.

<customErrors mode="On" defaultRedirect="defaultRedirect="~/Home/Error"">
<error statusCode="404" redirect="~/Home/NoPageFound"/>
<error statusCode="403" redirect="~/Home/Error"/>
<error statusCode="401" redirect="~/Home/Error"/>


By default customErrors will redirect a user to the defined error page with a HTTP 302 Redirect response. This will load error page with status 200 OK. This will have side effects like Google will start indexing those error pages this is explained nicely in the article posted about ASP.NET MVC 5 Error Pages and Error Logging by Dustin Moris.

In the next article we are going to see how to handle other http errors using Application_Error event in global.asax.

Back to top