ASP.NET

Unhandled Exceptions

In the last example page that threw an exception, ASP.NET responded by redirecting to the default error page. ASP.NET also lets you trap exceptions by setting up a handler for Error events fired by HttpApplication so that you may handle them more appropriately.

The easiest way to accomplish this is to define a handler in your HttpApplication-derived class within Global.asax. With the handler connected to the event, your application will receive notifications whenever something bad happens, and you can deal with it gracefully. For example, you might log the error before redirecting the user to an error page.

<script runat="server">
    void Application_Start(Object sender, EventArgs e) {
     }
    void Application_End(Object sender, EventArgs e) {
     }
    void Application_Error(Object sender, EventArgs e) {
      Exception ex = Server.GetLastError();

      // display the exception before redirecting
      System.Diagnostics.Debug.WriteLine("Error in app: " + ex);

      if (ex is HttpUnhandledException)
      {
          Server.Transfer("somethingbadhappened.aspx");
      }
    }

    void Session_Start(Object sender, EventArgs e) {
    }

    void Session_End(Object sender, EventArgs e) {
    }

</script>

The code above traps the exception before the redirection happens. This gives you the opportunity to log the exception (or, as in the example above, to show it in the System.Diagnosics.Debug context). You may also redirect users to a different page, if you want to hijack the exception handling before ASP.NET redirects to the page specified in Web.Config. Be sure to call Context.ClearError first to clear the error so ASP.NET won't generate its standard error page.