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 -->
     <compilation debug="true"/>
     <customErrors mode="On" defaultRedirect="MyErrorHandler.aspx"/>

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();

<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>

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();

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") ;

Further reading on error handling:

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:

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.


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

1 Comment

  • Please go through below link you will find very good information about custom error pages in

Comments have been disabled for this content.