Global error handling in ASP.NET MVC. Possible?

It seems that Application_Error in Global.asax is catching errors thrown during MVC runtime. There are other solutions that include overriding Controller.OnException.

Is it possible to create an error handler that will catch all errors from all controllers (including those generated by my code)?


source to share

2 answers

Yes - if you look at Global.asax the HandleErrorAttribute is added toGlobalFilterCollection

        filters.Add(new HandleErrorAttribute());


But by default, the HandleErrorAttribute will only handle internal server errors, that is, all exceptions that are not HttExceptions and HttpExceptions with error code 500. You can get this attribute to handle all exceptions and further customize the default behavior.


is the standard way to handle errors in mvc.



Like archilic, you don't even need to decorate your controllers / actions with [HandleError] as it's the default (in MVC3).

By mistake it will return the Error.cshtml view which, if you used the project template, is in views / shared.

You can customize it a bit if you like, the HandleErrorInfo model so you can pull the controller name, action, message, and stack trace out of it if you accidentally want to get a nice, customizable exception message. Here's one catch: you can't have any logic / operations on this page.

And you will have to enable custom errors in Web.config, otherwise you will get the standard yellowish screen:

    <customErrors mode="On"/>


And in customErrors, you can define one static fallback page if all else fails.



All Articles