Jon's Blog

.NET Development & More

ASP.NET: Improving Your Error Logging & Handling

One of the first things I like to setup when I am creating a new site is a customized error page and error logging.  To log all unhandled errors on your site you can add some code to the Application_Error event of your Global.asax file.  What I do is to grab the exception and then I use a static method of a helper class I have in my class library.  I pass the name of the web application where the error occurred and the exception itself.  In the helper method I can then extract the details I need from the exception and log it to a database table.

Global.asax.cs:

public const string APP_NAME = "Name of My App";

void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError().GetBaseException();
    SiteErrorLog.LogError(APP_NAME, ex);
}

 

Next, in the web.config you can setup your site so the user sees a nice, customized error page instead of the default ASP.NET error page.  Under the <system.web> node, add the following:

<customErrors mode="RemoteOnly" defaultRedirect="ErrorPage.aspx"></customErrors>

 

Now when your site is hit from a remote client (RemoteOnly) and an unhandled error occurs they will be redirected to the page you created (ErrorPage.aspx).  This is much nicer for the user of your site.