Wednesday, July 21, 2010

Error Catching, Handling and displaying in C# Asp.Net Web Application

Code for: C#, Asp.Net

This article explain how I handle and display web site errors.

I like to delegate control to a central place. It makes;
  • Code maintainability becomes stress free
  • Centralize place to tackle errors
  • Displaying errors can be uniform
  • The list goes on..

Create a WUC

I crate a web user control to show any message (MessageDisplay.ascx). Error or Information type of messages. This has the following controls
  • Image control
  • Label control to show the heading
  • Label control to show the message description

The three controls above can be changed depending on the message type. For an example show a critical error image or information image. Change the font colour border or any other property based on the message type.


Display page

Create a aspx file (Message.aspx) to get the request from the error capture module. This page will contain id parameter (Request.QueryString["id"]) this id is generated by the site application (see “Error Capture” section). This way you can pass different messages to “MessageDisplay” web user control. In our application we have a Db table to log all events, actions and errors. The Id is the unique row id of the log table. This way we can relate an error to an email or to a log entry.

Error capture

Capture them all. Lets capture all errors in “On Error” event of “Global.asax” file.


void Application_Error(object sender, EventArgs e)
{
    long lastErrorId = -1;
    string subject = string.Empty;
    string emailAdminAddress = "admin@this.com";

    Exception err = Server.GetLastError().GetBaseException();

    //Get the unique id, Write function will write an entry to the log table
    lastErrorId = AppHelper.Log.Write(err);

    //Send an email to admin.
    subject = "Error on site " + AppSettings.ApplicationName + " Id:" + lastErrorId.ToString();
    EmailClient.SendEmail(err, emailAdminAddress, subject);

    Server.ClearError();

    //Show the message to the user
    Response.Redirect("~/Messages/Message.aspx?id=" + lastErrorId);
}

Capturing and handling errors on pages

To make all work, the page has to do only one thing. Capture and throw.
try
    {
        // do something 
    }
    catch (Exception ex)
    {
        throw ex;
    }

In a nutshell

If there are any errors on aspx pages just trap and throw. The thrown error will go through the asp.net hierarchy and captured by Global.Asax file. Then call a dedicated aspx page which in turn call a web user control and show a neat a error.

Happy coding.