简体   繁体   English

ASP.NET中的全局错误处理

[英]Global error handling in ASP.NET

Is there anything wrong with catching errors in an ASP.NET application globally (eg: Global.asax)? 在全局ASP.NET应用程序中捕获错误有什么问题(例如:Global.asax)? I have viewed the question Good error handling practice and it doesn't really say too much about this. 我已经看过一个好的错误处理实践的问题,并没有真正说太多。

My experience has been excluding some very specific circumstances (such as transactions) most of the ASP.NET applications we are writing are along the lines of 我的经验是排除了一些非常具体的情况(例如事务),我们编写的大多数ASP.NET应用程序都是如此

void ButtonEventHandler(object sender, EventArgs e) {
    Page.Validate();
    if (Page.IsValid) {
        //Do a database insert or update thru relevant datalayers.
        //If its a transaction then we rollback internally and rethrow
        //the exception.
    }
}

Why not just have a global exception handler? 为什么不只有一个全局异常处理程序? Usually (at this point) the only thing I can do is abort the operation gracefully and tell the user to try again. 通常(此时)我唯一能做的就是优雅地中止操作并告诉用户再试一次。

The global place to handle uncatched Exceptions would be in Global.asax by handling Application_Error . 通过处理Application_Error ,处理未捕获的异常的全局位置将在Global.asax中 As John pointed out, you should always handle exceptions as close as possible to where they might occur and react appropriately. 正如约翰所指出的那样,你应该尽可能地接近可能发生的异常,并做出适当的反应。

I think so. 我认同。 You should catch exceptions that you might expect on a particular operation as close to it as possible, and behave appropriately, but barring that (or perhaps following it after it does some clean-up and rethrows) a global handler that logs the exception and goes to a general 500 response is a good default behaviour. 您应该捕获特定操作可能期望的异常,尽可能接近它,并且行为恰当,但禁止(或者在它进行一些清理和重新抛出之后跟随它)一个记录异常的全局处理程序一般500响应是一个很好的默认行为。

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

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