Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Custom Error Pages in ASP.NET



Just like other .NET applications, ASP.NET applications can take advantage of exceptions to catch and handle runtime errors that occur in the code. Admittedly, wrapping a piece of code with a try/catch block makes programming much simpler while offering a single point of control for errors. However, employing this technique on a large scale may result in a dramatic loss of performance. Exceptions are meant to target exceptional events that aren’t predictable in other ways and should not be used to control the normal flow of the program.

When an exception occurs in an ASP.NET application, the CLR tries to find a block of code willing to catch it. Exceptions walk their way up the call stack until the root is reached. If no proper handler shows up along the way, the exception gains the rank of unhandled exception and causes the CLR to throw a system-level exception. How should you deal with unhandled exceptions in ASP.NET applications?

When an unrecoverable error occurs in an ASP.NET page, the user always receives a page that, more or less nicely, informs that something went wrong at a certain point of execution. The typical error page differs for local and remote users. By default, local users, namely any user accessing the application through the local host, receives a page that includes a lot of technical details. The page includes the call stack—that is, the chain of method calls leading up to the exception—and a brief description of the error. Additional source-code information is added if the page runs in debug mode. For security reasons, remote users receive a less-detailed page that simply mentions that a runtime error has occurred.

Exception handling is a powerful mechanism to trap code anomalies and recover or degrade gracefully. By design, though, exception handling requires you to know exactly the points in the code where a given exception, or a given set of exceptions, can occur. Exceptions raised outside any interception points you may have arranged become unhandled exceptions and originate error pages.

ASP.NET provides a couple of global interception points for you to handle errors programmatically, at either the page level or the application level. To catch any unhandled exceptions wandering around a particular page, you define a handler for the Error event.

protected void Page_Error(object sender, EventArgs e)
{
    // Capture the error  
    Exception ex = Server.GetLastError();

    // Resolve the error page based on the exception occurred
    if (ex is NotImplementedException)
       Server.Transfer("/notimplementedexception.aspx");
    else
       Server.Transfer("/apperror.aspx");

    // Clear the error
    Server.ClearError();
}

You can find out about the raised exception through the GetLastError method of the Server object. In the Error handler, you can transfer control to a particular page and show a personalized, and exception-specific, message to the user. The control is transferred to the error page and the URL in the address bar of the browser doesn't change.

A page Error handler only catches errors that occur within a particular page. This means that each page that requires error handling must point to a common piece of code or define its own handler.

You can also create a global error handler at the application level that catches all unhandled exceptions and routes them to the specified error page. To do that, you add a global.asax file to your application and write code in the predefined Application_Error stub.

void Application_Error(Object sender, EventArgs e) { 
   :
}

You could also do something useful in this event handler, like send an e-mail to the site administrator or write to the Windows event log, saying that the page failed to execute properly.


Dino Esposito is Wintellect's ADO.NET and XML expert, and a trainer and consultant based in Rome, Italy. Dino is a contributing editor to Windows Developer Network and MSDN Magazine, and the author of several books for Microsoft Press including Building Web Solutions with ASP.NET and ADO.NET and Applied XML Programming for .NET. Contact Dino at [email protected].



Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.