Trapping Application Errors

Web page exceptions can be handled in a few different ways.
     •        A try/catch block can be defined directly around the (potentially) offending code.
     •        A Page_Error() event handler can be added to the page’s code-behind file.
     •        A global error handler can be defined in the Global.asax’s
Application_Error() event handler.
     •        A dedicated general error page can be defined in the Web.config file.

Assume that you have a Button’s “Click” event handler on a page, which attempts to open a file on the Web
server - which does not exist! At runtime, the CLR will throw a FileNotFoundException object. Notice in the
following code that the exception is not being caught …


public partial class _Default : System.Web.UI.Page
{
 protected void btnOpenFile_Click(object sender, EventArgs e)
 {
   // This is the offending line.
   System.IO.File.OpenText(Server.MapPath("IDontExist.xml"));
 }
}



When this event is raised, we are presented with a unhandled exception:


















When a Page_Error event handler is used, unique functionality for this page can be defined and executed (note
the hard-coded file name in the code below). Use the
Server.GetLastError() method to extract the
underlying
System.Exception derived type. Once you have processed the error, use Server.ClearError() to
inform the runtime that the error has been dealt with. If you forget to do so, the runtime will clobber your
custom error logic with the same standard CLR error.


public partial class _Default : System.Web.UI.Page
{
 protected void btnOpenFile_Click(object sender, EventArgs e)
 {
   // This is the offending line.
   System.IO.File.OpenText(Server.MapPath("IDontExist.xml"));
 }

 protected void Page_Error(object sender, EventArgs e)
 {
   Exception ex = Server.GetLastError().GetBaseException();
   Response.Write("<hr/>We're sorry. The file, IDontExist.xml, " +
     "cannot be loaded because:<br/>" + ex.Message + "<br/><hr/>");

   // Log the error to the error database...

   // Clear the error, or else ASP.NET will ignore my response
   // and display its own error message!
   Server.ClearError();
 }
}


When executed, the page displays a friendlier error message:














If an *.aspx file does not handle a raised exception, the Application_Error() event handler in Global.asax can
handle it. Application_Error() is your last chance to handle an exception before the end user sees an unsightly
error page. It must be “generic” enough to handle errors that occur on any Web page.

Just update
Application_Error() in the Global.asax file as so. Note the “more generic” error message:


void Application_Error(object sender, EventArgs e)
{
 Exception ex = Server.GetLastError().GetBaseException();
 Response.Write("<hr/>We're sorry. A problem occurred because:<br/>" +
   ex.Message + "<br/><hr/>");

 // Log the error to the error database...

 // Clear the error, or else ASP.NET will ignore my response
 // and display its own error message!
 Server.ClearError();
}


Giving us this error message:














A more real-world implementation of Application_Error() might:
     •        Forward the user to a custom error page
     •        Email the system administrator regarding the error, etc.
     •        Give a less-detailed message to the Web user while log an extremely detailed error message to a
              dedicated error database.

Finally, an error page can be set to run by default if an exception occurs on any page. Just specify the default
error page in the customErrors section of the Web.config file. In the example below, two error pages are
specified by Web.config. One for generic HTTP errors and another for HTTP 404 errors.


<customErrors defaultRedirect="errorStatus.htm" mode="On">
 <error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>



If someone tried navigating to a Web page that doesn’t exists, they’ll be brought to the page, FileNotFound.
htm. Any other error will redirect the user to errorStatus.htm.
Trapping Application Errors
Table of Contents
Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used exclusively as an
online learning aid.  Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials
Services