简体   繁体   中英

Global error handling in ASP.NET MVC. Possible?

It seems that Application_Error in Global.asax only catch errors generated by MVC runtime. There are other solutions that involve overriding Controller.OnException.

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

Yes - if you take a look at Global.asax, HandleErrorAttribute is added to GlobalFilterCollection

        filters.Add(new HandleErrorAttribute());

But the default HandleErrorAttribute will handle only internal server errors, that is all the exceptions that are not HttException and HttpExceptions with error code 500. You can derive from that attribute to handle all of exceptions and further customize default behavior.

HandleErrorAttribute is the standard way of error-handling in asp.net mvc.

Just like archil said, you don't even have to decorate the controllers/actions with [HandleError] since it's on by default (in MVC3).

On error it will return the Error.cshtml view which, if you used the project template, is in the Views/Shared.

You can customize it a little bit if you want, the model is HandleErrorInfo so you can pull the controller name, action, message and stack trace out of there if by any chance you want a nice, custom exception message. There's a one catch here: you can't have any logic/operations on this page.

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

<system.web>
    <customErrors mode="On"/>
    ...
</system.web>

And in the customErrors you can define one static fallback page, in case when everything else fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM