Custom Error Pages in ASP.NET

First, turn on custom error reporting in the web.config and name the file you will use as your default handler:

<!-- Web.Config -->
<configuration>
   <system.web>
     <compilation debug="true"/>
     <customErrors mode="On" defaultRedirect="MyErrorHandler.aspx"/>
   </system.web>
</configuration>

At its simplest, that's all there is to it. Apologize to the user and provide some links back to what they were doing before the error. But what were they doing? What is the error? You might be disappointed that variations on the following don't work in MyErrorHandler.aspx:

<%@ Page Language="C#" %>
<script runat="server">

private void Page_Load( object src, EventArgs e ) {
   Exception objError = Server.GetLastError();
   lblMessage.Text=objError.Message;
   lblSource.Text=objError.Source;
   Server.ClearError();
}

</script>
<html><head><title>Server Error</title></head>
<body><form runat="server">
   <p><asp:label id="lblMessage" runat="server" /></p>
   <p><asp:label id="lblSource" runat="server" /></p>
</form></body></html>

The error is past tense by the time you hit the handler page. How do you find it? Keep reading.

The simplest thing to do is to catch and store the Exception inside the Application bag right in your global.asax (or a global.asax.cs codebehind):

<%@ Import Namespace="System.IO" %>
<script language="C#" runat="server">
 
protected void Application_Error( object src, EventArgs e ) {
   Exception objError = Server.GetLastError();
   HttpContext.Current.Application.Add("lastException",objError);
   Server.ClearError();
}
 
</script>

And then retrieve and the display the Exception object's properties (Exception.Message, Exception.Source, Exception.StackTrace, or Exception.TargetSite.Name) inside MyErrorHandler.aspx (as named in your web.config).

private void Page_Load( object src, EventArgs e ) {
   Dim objError As System.Exception = HttpContext.Current.Application.Get("lastException") ;
   lblMessage.Text=objError.GetBaseException.Message;
   lblStackTrace.Text=objError.GetBaseException.StackTrace;
}
...

Further reading on error handling: http://www.c-sharpcenter.com/asp.net/customerrors.htm

Advanced User Note: On a busy site, use of the Application object impedes scalability. Application objects are a late-bound kludge to help migrate from Classic ASP to .NET. Ideally you should grab the Exception properties into static fields in some sort of Global class which could then be accessed by the custom error page.

Further reading on the Application object: http://www.eggheadcafe.com/articles/20030211.asp

Caveat: Recognize that on a high traffic site which generates nearly simultaneous errors, since this method records the last error in the Application and not the last error in the Session, by the time the Custom Error page is displayed a user could conceivably get someone else's error message. Though not a common problem on most sites, it could potentially confuse whoever is debugging the problem.

A solution to this would be to write the error into a log right when it is raised and debug with the log. The article on error handling above covers writing to the Event Log.

Enjoy!

[Updated 2003-09-18: Corrected the sample code which didn't properly grab the error from the Application object, doh eh!]

Published Wednesday, April 23, 2003 8:39 PM by erobillard
Filed under: ,

Comments

Wednesday, April 23, 2003 7:48 PM by Jason Priestas

# re: Custom Error Pages in ASP.NET

Great read, thanks! I have two config settings for both logging and emailing error reports to a support inbox when they shake down - all handled through an 'ErrorHandler' object. I never looked at the defaultRedirect attribute before, though.
Friday, January 09, 2004 8:42 PM by Tekmaven

# re: Custom Error Pages in ASP.NET

I just realized that the last Page_Load event is declared with C# code, but the interior code is in VB.NET ;-) whoops!
Monday, March 01, 2004 3:23 PM by asper

# re: Custom Error Pages in ASP.NET

# re: Custom Error Pages in ASP.NET 1/9/2004 8:42 PM Tekmaven

uahhuahua
Monday, March 01, 2004 4:37 PM by Eli Robillard

# re: Custom Error Pages in ASP.NET

Sonnova! Well, the better source for all of this information is now an article on MSDN: http://msdn.microsoft.com/asp.net/default.aspx?pull=/library/en-us/dnaspp/html/customerrors.asp

And, it has both VB and C# code.

Enjoy,
-e.
Thursday, March 25, 2004 3:20 PM by John

# re: Custom Error Pages in ASP.NET

Error: System.NullReferenceException: Object reference not set to an instance of an object

I tried to run the example below and got an object reference message. Any idea what I am missing.
private void Page_Load( object src, EventArgs e ) {
Exception objError = Server.GetLastError();
lblMessage.Text=objError.Message;
lblSource.Text=objError.Source;
Server.ClearError();
}
Friday, April 02, 2004 6:22 AM by prasad patnaik

# re: Custom Error Pages in ASP.NET

i m facing the same find no way out
Wednesday, April 21, 2004 11:02 AM by Seong Bae

# re: Custom Error Pages in ASP.NET

In C#, it complains about not being able to convert the object to System.Exception when trying to assign lastException to objError.
Any suggestion? :)
Thursday, June 03, 2004 5:47 AM by Andrew

# re: Custom Error Pages in ASP.NET

How do I determine exactly which HTTP error was thrown (403/404/500)? Does it get listed in the message property?

I want to log 404 errors to a database and all other errors to the eventlog. How would I do this?
Tuesday, June 22, 2004 8:12 PM by Paul

# re: Custom Error Pages in ASP.NET

This is how you find a 404 Error.

if (exToHandle.GetType().FullName == "System.IO.FileNotFoundException")
{
//This is a Server 404 Error
}

I don't know what some of the others would be such as 403, 500, etc. I am looking for a list of these.

To write into the event log, use this function:

EventLog.WriteEntry ("Your App Name", ex.ToString());
Tuesday, June 29, 2004 1:24 PM by bbbd

# re: Custom Error Pages in ASP.NET

gitgiyuiy
Wednesday, June 30, 2004 3:05 PM by Oleg

# re: Custom Error Pages in ASP.NET

One of the problems with this code is racing conditions.

HttpContext.Current.Application.Add("lastException",objError);

If 2 people get an error at the same time, the first user to submit it may submit the 2nd user's error. This is because Application collection is shared accross all users.

Microsoft provides HttpContext.Current.Application for backward compatibility with ASP. They suggest you use static class members instead, which are also shared by all users. Therefore, this doesn't solve the problem. Storing error in session may do the trick but it will not always work. Session may not be available.

-Oleg.
Wednesday, June 30, 2004 3:06 PM by Oleg

# re: Custom Error Pages in ASP.NET

Paul, don't compare strings, use "is" instead:


if (exToHandle is System.IO.FileNotFoundException)
{
//This is a Server 404 Error
}

Friday, July 20, 2007 3:26 PM by Ron

# re: Custom Error Pages in ASP.NET

Same problem no answer.

Error: System.NullReferenceException: Object reference not set to an instance of an object

Leave a Comment

(required) 
(required) 
(optional)
(required)