Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of [HandleError] over Application_Error

I'm aware there are plenty of questions in SO about Error handling in ASP.NET MVC.

I see, mostly people are trying to achieve things in three ways:

  1. Create a BaseController and override the OnException method

  2. Using [HandleError] or custom exception filters.

  3. Application_Error event in global.asax.cs

The first two ways can't handle all the exceptions and they do only that are raised by action methods/filters, so obviously the third one is going to be the best approach for a global exception handler.

My question is why I should go for [HandleError] approach? What benefits it brings that I can't get through Application_Error?

Finally, do I want to take the customErrors section serious at all in a MVC application?

Note: My requirement is usual. Whenever an exception occurs, log it and return a custom error page. The custom error page may change depend upon the status code.

like image 259
VJAI Avatar asked Apr 27 '12 16:04

VJAI


People also ask

What is HandleErrorAttribute?

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.

How exception is handled globally in C#?

An ExceptionFilterAttribute is used to collect unhandled exceptions. You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions.


1 Answers

The most obvious is that [HandleError] allows you to handle errors differently in different controllers and actions. Its much more elegant than some kind of switch statement in your Application_Error handler.

Another benefit is that [HandleError] still has access to the controller and all the MVC goodness that comes with it, so you can still return a View or call another action. Once you fall out to Application_Error, you've lost ControllerContext and you don't really have options left to you except to redirect.

like image 59
bhamlin Avatar answered Oct 14 '22 01:10

bhamlin