简体   繁体   English

ASP.NET MVC中的全局错误处理。可能?

[英]Global error handling in ASP.NET MVC. Possible?

It seems that Application_Error in Global.asax only catch errors generated by MVC runtime. 似乎Global.asax中的Application_Error只捕获MVC运行时生成的错误。 There are other solutions that involve overriding Controller.OnException. 还有其他涉及覆盖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 是 - 如果您查看Global.asax, HandleErrorAttribute将添加到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将只处理内部服务器错误,即所有不是HttException的异常和错误代码为500的HttpExceptions。您可以从该属性派生以处理所有异常并进一步自定义默认行为。

HandleErrorAttribute is the standard way of error-handling in asp.net mvc. HandleErrorAttribute是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). 就像archil所说的那样,你甚至不需要用[HandleError]来装饰控制器/动作,因为它默认是打开的(在MVC3中)。

On error it will return the Error.cshtml view which, if you used the project template, is in the Views/Shared. 出错时,它将返回Error.cshtml视图,如果您使用项目模板,则该视图位于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. 如果需要,您可以稍微自定义它,模型是HandleErrorInfo,因此您可以将控制器名称,操作,消息和堆栈跟踪拉出来,如果您想要一个漂亮的自定义异常消息。 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: 而且您必须在Web.config中启用自定义错误,否则您将获得标准的黄色屏幕:

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

And in the customErrors you can define one static fallback page, in case when everything else fails. 在customErrors中,您可以定义一个静态回退页面,以防其他所有内容失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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