Global error handling in ASP.NET

2019-03-26 04:58发布

Is there anything wrong with catching errors in an ASP.NET application globally (eg: 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

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.

2条回答
贪生不怕死
2楼-- · 2019-03-26 05:47

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.

查看更多
何必那么认真
3楼-- · 2019-03-26 05:48

The global place to handle uncatched Exceptions would be in Global.asax by handling Application_Error. As John pointed out, you should always handle exceptions as close as possible to where they might occur and react appropriately.

查看更多
登录 后发表回答