Error Handling in ASP.NET

Summary

Exceptions and exception classes

Information relating to exceptions and exception classes and how to deal with exception can be found in .NET Design section under Exceptions.

Page-Level Error Handling

In general, you will not be able to plan for, catch and recover from every possible exception that could occur within a page. ASP.NET helps by offering two techniques to handle page-level errors :

Using the Page class Error event

The Page class has an Error event that is fired when an un-handled exception occurs within a page. The Error event handler is typically used perform various clean-up functions and to redirect the user to a specific error page. The following code shows to handle un-handled exceptions/errors by providing a handler for the Error event of the associated Page class:

<%@ Page language="c#" Codebehind="default.aspx.cs" AutoEventWireup="false" Inherits="ErrorHandling.PageLevelErrorHandling" %>
<HTML>
    <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <asp:Label id="Label1" runat="server" Font-Size="Large">Some HTML ....</asp:Label>
        </form>
    </body>
</HTML>

...
public class PageLevelErrorHandling : System.Web.UI.Page
{
    protected System.Web.UI.WebControls.Label Label1;

    private void Page_Load(object sender, System.EventArgs e)
    {
        // This simulates an unhandled exception
        throw new InvalidOperationException("There is no connection to the database");
    }

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
        InitializeComponent();
        base.OnInit(e);
    }

    private void InitializeComponent()
    { 
        this.Load += new System.EventHandler(this.Page_Load);
        this.Error += new System.EventHandler(this.Page_Error);
    }
    #endregion

    // Error event handler
    private void Page_Error( object o, EventArgs e)
    {
        // Obtain a reference to the last error reported for this request then write
        // out the details of that error

        Response.Write( "An error has occurred:<BR>");
        Response.Write( Server.GetLastError().Message );

        // Clear the error
        Context.ClearError();
    }
}

The following shows output from running the previous code. Note that when an unhandled exception occurs, normal HTML page processing halts and the error handler is invoked:

     

Using the @Page directive to handle page redirection

With this page-level error-handling technique, the @Page directive uses the ErrorPage attribute to define a target URL for redirection in the event of an unhandled exception (i.e., there was no Error event handler). Note that it might be necessary to update the Web.Config file to enable page redirection on error

<configuration>
    <system.web>
        <CustomErrors mode="On|RemoteOnly" />
    <system.web>
<configuration>

When mode is set to On, the page redirection on error will always take place. When mode is set to RemoteOnly, the page redirection on error will only occur if the web site is accessed remotely (note from localhost)  

In the following screens, the code behind file fired an unhandled exception in the Page_Load function. Because no Error event handler was supplied, ASP.NET will redirect the user to the specified error page. The first screen shot illustrates output if <CustomError> tag in Web.Config was set to RemoteOnly and then accessed locally. The second screen shot illustrates output if <CustomError> tag in Web.Config was set to On and then accessed locally:

<!-- HTML with error redirection -->
<%@ Page language="c#" Codebehind="PageLevel_Redirect.aspx.cs" AutoEventWireup="false"
Inherits="ErrorHandling.PageLevel_Redirect" ErrorPage="MyErrorPage.htm" %>
...

Application-Level Error Handling

Page-level error handling is most appropriate for individual pages such as invalid use of exceptions. However, this method can become very tedious especially if you are developing hundreds of ASP.NET pages. ASP.NET addresses this situation by handling errors at the application level. Like Page-level error handling, there are two common techniques - the Application object Error event handler and page-redirection.

Using the Application Error event handler

The Error event handler is found in Global.asax file. The purpose of this file to specify the following::

Application-level error handling is handled by Code Declaration Blocks. The Error event of the Application class is fired when an exception is left unhandled. The handler is usually found in Global.asax:

protected void Application_Error( object o, EventArgs e)
{
    // Process the error using of the two methods discussed below
    ...
    
    // Clear all exceptions from the current request
    Context.ClearError();
}

The EventArgs parameter contains information related to the error, but unfortunately, it does not contain any information related to the exception. Despite the lack of the exception as a parameter, there are a couple of ways to get information about the exception:

Note in the code above that Context.ClearError() should always be called after the exception has been handled. If the ClearError() has not been cleared, the exception will still show up on the client's browser. The following code illustrates:]

protected void Application_Error(Object sender, EventArgs e)
{
    // Get erorr information
    System.Exception ex1 = Context.Error;
    Response.Write( "Context.Error - The following error occured: " + ex1.Message );
    Response.Write( "<BR>" );

    // Another way to get error information
    System.Exception ex2 = Server.GetLastError();
    Response.Write( "Server.GetLastError - The following error occured: " + ex2.Message );

    // Finally, clear the error
    Context.ClearError();
}

      

Using page redirection

Page redirection when an application-level error happens cannot be done via the @Page directive because this directive is page-specific. Instead, the <CustomError> section discussed previously can be used to enable page redirection when an application level error is fired. Additionally, you can customize error pages for certain error numbers using the <error> sub-element. For example, you can redirect error 404 to one page, while redirecting all other HTTP errors to another page.

<configuration>
    <system.web>
        <CustomErrors mode="On|RemoteOnly" defaultRedirect="MyCustomErrors.aspx?Err=Unspecified"/>
            <error statuscode="404" redirect="MyCustomErrors.aspx?Err=Some+Meaningful+Error+Message"/>
    <system.web>
<configuration>