.netCoders Contact Us
Search:

Error Handling

Apart from the try/catch language constructs and exception handling framework, you can configure ASP.NET and IIS to display custom error pages for unhandled events. You can also implement application wide error event handling using the global.asax file.

Custom Error Pages

Configuring custom error pages is a two-fold process. Remember that ASP.NET is an IIS ISAPI extension, and that IIS first receives the request. Depending on the file extension of the requested resource, IIS will forward the request to the appropriate ISAPI extension. Therefore, to supply custom error pages, you not only have to set the configuration for ASP.NET, but IIS and non-ASP.NET files as well. For example, if someone requests the file /missing/file.shtm, the File Not Found page configured in IIS will be displayed.

To configure IIS for custom error pages, open up the Internet Services Manager console. Right-click the website root or subdirectory you want to configure, and select Properties from the context menu. Next, select the Custom Errors tab. This tab shows mappings for HTTP Error Messages and the corresponding files displayed. To change an entry, click on the entry to select it, and then click the Edit Properties button. In the subsequent dialog, you can indicate a file or URL to display.

Configuring ASP.NET error pages involves the web.config file. Because this file is text-based, you can make changes to your custom error handling and deploy the updates to your servers simply by copying the file. To add custom error handling, change or add a <customErrors> tag with the mode set to "on" [local and non-local clients] or "remoteonly" [non-local clients only]. Setting the value to "remoteonly" allows you to use the local server machine to get more detailed error messages, and let friendly pages be displayed for non-local users. This is the default value.

Within the <customerErrors> tag, you can add <error> tags indicating which page [via the redirect attribute] should be displayed for a given HTTP error code [the statusCode attribute]. The following example shows a configuration where File Not Found and general Server Errors have custom error pages.

<configuration>
<system.web>
<!-- CUSTOM ERROR MESSAGES
Set mode="on" or "remoteonly" to enable custom error messages, "off" to disable. Add
<error> tags for each of the errors you want to handle.
-->
<customErrors defaultRedirect="GenericError.aspx" mode="On">
<error statusCode="404" redirect="404FileNotFound.aspx" />
<error statusCode="500" redirect="500ServerError.aspx" />
</customErrors>
</system.web>
</configuration>

Page-Level Error Handling

Errors can also be handled at the page level using the Page class's Error event. This event is fired when an unhandled exception occurs during the processing of the page at run time. Within the event handler, you can still access the Request and Response objects, allowing you to display messages to the user. The following method declaration from an ASP.NET page shows a basic error handler.

<script language="C#" runat="server">
void Page_Error(Object source, EventArgs e)
{
Response.Write("We're sorry. We've encountered an error while processing your request.");
}
</script>

Application-Level Error Handling

Using the global.asax file, you can override the System.Web.HttpApplication class's Application_Error method to provide your own application-wide error handling. Perhaps you want your system administrators to receive an email, or the error details to be written to a log file. The following code snippet from a web application global.asax file shows messages being logged to the Event Log.
public class Global : System.Web.HttpApplication
{
    protected void Application_Error(Object sender, EventArgs e)
    {
        //Get error Details
        string strMessage = "\n\nURL:\n http://localhost/" + Request.Path
            + "\n\nMESSAGE:\n " + Server.GetLastError().Message
            + "\n\nSTACK TRACE:\n" + Server.GetLastError().StackTrace;

        // Insert into event log
        System.Diagnostics.EventLog objLog = new System.Diagnostics.EventLog();
        objLog.WriteEntry(strMessage, System.Diagnostics.EventLogEntryType.Error);
    }
}