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:
Create a BaseController
and override the OnException
method
Using [HandleError]
or custom exception filters.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With