Catching errors in Global.asax

2019-03-25 04:02发布

问题:

I have the following in my Global.aspx which is meant for handling errors:

void Application_Error(object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    if (exception != null)
    {
        //Log
        if (HttpContext.Current.Server != null)
        {
           HttpContext.Current.Server.Transfer("/siteerror.aspx");
        }
    }
}

This works for the most part, but sometimes does not get into Server.Transfer. For some reason HttpContext.Current.Server is null. I figured out where this happens: when errors occur in a user control and in my business logic classes. Am I missing something here?

Thanks

回答1:

Application_Error block can catch exception anytime between application life cycle.

Application life cycle is parent of Session life cycle as you can understand there can be many sessions within a single application.

Thus you may have HttpContext.Current null at certain errors occured before creating session or after expiring of sessions.

If you want to write session specific error redirects you should check for Null of current HttpContext always.

You can also use Server.GetLastError to know the error details occured and write your error page redirect through CustomError tag in web.config

See the following link

http://weblogs.asp.net/scottgu/archive/2006/08/12/Tip_2F00_Trick_3A00_-Show-Detailed-Error-Messages-to-Developers.aspx



回答2:

Application Errors can occur at any time - including when no connection is present.

For example, if a background thread is processing and causes an exception.