Export (0) Print
Expand All

Complete Example for Error Handlers

This code example includes elements for both page-level and application-level exception handling.

The example consists of the following files:

  • Web.config

  • Global.asax

  • Default.aspx

  • ExceptionUtility (to be put in the App_Code folder)

  • GenericErrorPage.aspx

  • HttpErrorPage.aspx

  • Http404ErrorPage.aspx

  • DefaultRedirectErrorPage.aspx

Web.config

The following example shows the Web.config file. The customErrors section specifies how to handle errors that occur with file types that are mapped to ASP.NET, such as .aspx, .asmx, and .ashx files. (In IIS 6.0 and in IIS 7.0 in classic mode, static content files such as .html and .jpg files are not mapped to ASP.NET.)

The settings in the example customErrors section cause any unhandled HTTP 404 (file not found) errors to be directed to the Http404ErrorPage.aspx file. These HTTP 404 errors would occur if a request were made for an .aspx file, .asmx file, and so on and if the requested file did not exist. All other unhandled errors in ASP.NET files are directed to the DefaultRedirectErrorPage.aspx file.

If static content files are not handled by ASP.NET, a request for a nonexistent .html or .jpg file does not cause a redirect to the Http404ErrorPage.aspx file. If you want ASP.NET to handle requests for all file types, you can configure IIS to map file-name extensions to ASP.NET.

NoteNote

In the example, the mode attribute is set to "On" so that you can error messages when you run the example in Visual Studio. In a production environment, this setting would normally be "RemoteOnly". ASP.NET then renders error pages to external users. If a request is made on the server computer (localhost), ASP.NET renders a page with detailed error information.


<configuration>
  <appSettings/>
  <connectionStrings/>
  <system.web>
    <compilation debug="true" />

    <!-- Turn on Custom Errors -->
    <customErrors mode="On" 
      defaultRedirect="DefaultRedirectErrorPage.aspx">
      <error statusCode="404" redirect="Http404ErrorPage.aspx"/>
    </customErrors>

  </system.web>
</configuration>


Global.asax

The following example shows the Global.asax file

Security noteSecurity Note

Never set the mode attribute in the customErrors element to "Off" in the Web.config file if you have not created an Application_Error handler in the Global.asax file. If the mode is set to "Off," potentially compromising information about your Web site can be exposed to anyone who can cause an error to occur on your site.


void Application_Error(object sender, EventArgs e)
{
  // Code that runs when an unhandled error occurs

  // Get the exception object.
  Exception exc = Server.GetLastError();

  // Handle HTTP errors
  if (exc.GetType() == typeof(HttpException))
  {
    // The Complete Error Handling Example generates
    // some errors using URLs with "NoCatch" in them;
    // ignore these here to simulate what would happen
    // if a global.asax handler were not implemented.
      if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
      return;

    //Redirect HTTP errors to HttpError page
    Server.Transfer("HttpErrorPage.aspx");
  }

  // For other kinds of errors give the user some information
  // but stay on the default page
  Response.Write("<h2>Global Page Error</h2>\n");
  Response.Write(
      "<p>" + exc.Message + "</p>\n");
  Response.Write("Return to the <a href='Default.aspx'>" +
      "Default Page</a>\n");

  // Log the exception and notify system operators
  ExceptionUtility.LogException(exc, "DefaultPage");
  ExceptionUtility.NotifySystemOps(exc);

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


ExceptionUtility

The following example shows the ExceptionUtility file. Error logs might be directed to the computer's ErrorLog file, or, if the computer is part of a Web farm, the error log might be recorded in a globally available text file, or even a database. You might also need to immediately notify system administrators of a problem.

The ExceptionUtility class in the example has two static methods: one to log the exception, and one to notify system administrators. How those methods are implemented in your code depends on the needs of your organization. For this example, you must grant write permissions to the ASP.NET worker process account (by default, this is NETWORK SERVICE) for the App_Data folder to enable the application to write to the error log.


using System;
using System.IO;
using System.Web;

// Create our own utility for exceptions
public sealed class ExceptionUtility
{
    // All methods are static, so this can be private
    private ExceptionUtility()
    { }

    // Log an Exception
    public static void LogException(Exception exc, string source)
    {
        // Include enterprise logic for logging exceptions
        // Get the absolute path to the log file
        string logFile = "App_Data/ErrorLog.txt";
        logFile = HttpContext.Current.Server.MapPath(logFile);

        // Open the log file for append and write the log
        StreamWriter sw = new StreamWriter(logFile, true);
        sw.WriteLine("********** {0} **********", DateTime.Now);
        if (exc.InnerException != null)
        {
            sw.Write("Inner Exception Type: ");
            sw.WriteLine(exc.InnerException.GetType().ToString());
            sw.Write("Inner Exception: ");
            sw.WriteLine(exc.InnerException.Message);
            sw.Write("Inner Source: ");
            sw.WriteLine(exc.InnerException.Source);
            if (exc.InnerException.StackTrace != null)
            {
                sw.WriteLine("Inner Stack Trace: ");
                sw.WriteLine(exc.InnerException.StackTrace);
            }
        }
        sw.Write("Exception Type: ");
        sw.WriteLine(exc.GetType().ToString());
        sw.WriteLine("Exception: " + exc.Message);
        sw.WriteLine("Source: " + source);
        sw.WriteLine("Stack Trace: ");
        if (exc.StackTrace != null)
        {
            sw.WriteLine(exc.StackTrace);
            sw.WriteLine();
        }
        sw.Close();
    }

    // Notify System Operators about an exception
    public static void NotifySystemOps(Exception exc)
    {
        // Include code for notifying IT system operators
    }
}


Default.aspx

The following example shows the Default.aspx page. This file provides several buttons, each of which raises a different exception. The Page_Error handler on the page displays an error page and logs some of these errors. Unhandled errors are passed to the Application_Error handler in the Global.asax file. The Application_Error handler displays an error page and logs some of the remaining errors. Any errors that are still not handled are directed to the page indicated by the customErrors section of Web.config file.


<%@ Page Language="C#" %>

<script runat="server">
  protected void Submit_Click(object sender, EventArgs e)
  {
    string arg = ((Button)sender).CommandArgument;

    switch (arg)
    {
      case "1":
        {
          // Exception handled on the Generic Error Page
          throw new InvalidOperationException("Button 1 was clicked");
          break;
        }
      case "2":
        {
          // Exception handled on the current page
          throw new ArgumentOutOfRangeException("Button 2 was clicked");
          break;
        }
      case "3":
        {
          // Exception handled by Application_Error
          throw new Exception("Button 3 was clicked");
          break;
        }
      case "4":
        {
          // Exception handled on the Http 404 Error Page
          Response.Redirect("NonexistentPage.aspx");
          break;
        }
      case "5":
        {
          // Exception handled on the Http Error Page
          Response.Redirect("NonexistentPage-NoCatch.aspx");
          break;
        }
      case "6":
        {
          // Exception handled on the Generic Http Error Page
            Response.Redirect("NonexistentPage-NoCatch.aspx/" + new string('x', 500));
          break;
        }
    }
  }
  private void Page_Error(object sender, EventArgs e)
  {
    // Get last error from the server
    Exception exc = Server.GetLastError();

    // Handle exceptions generated by Button 1
    if (exc is InvalidOperationException)
    {
      // Pass the error on to the Generic Error page
      Server.Transfer("GenericErrorPage.aspx", true);
    }

    // Handle exceptions generated by Button 2
    else if (exc is ArgumentOutOfRangeException)
    {
      // Give the user some information, but
      // stay on the default page
      Response.Write("<h2>Default Page Error</h2>\n");
      Response.Write("<p>Provide as much information here as is " +
        "appropriate to show to the client.</p>\n");
      Response.Write("Return to the <a href='Default.aspx'>" +
          "Default Page</a>\n");

      // Log the exception and notify system operators
      ExceptionUtility.LogException(exc, "DefaultPage");
      ExceptionUtility.NotifySystemOps(exc);

      // Clear the error from the server
      Server.ClearError();
    }
    else
    {
      // Pass the error on to the default global handler
    }
  }
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head id="Head1" runat="server">
  <title>Exception Handler Page</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <h2>
      Default Page</h2>
    <p>
      Click this button to create an InvalidOperationException.<br />
      Page_Error will catch this and redirect to 
      GenericErrorPage.aspx.<br />
      <asp:Button ID="Submit1" runat="server" 
        CommandArgument="1" OnClick="Submit_Click"
        Text="Button 1" />
    </p>
    <p>
      Click this button to create an ArgumentOutOfRangeException.<br />
      Page_Error will catch this and handle the error.<br />
      <asp:Button ID="Submit2" runat="server" 
        CommandArgument="2" OnClick="Submit_Click"
        Text="Button 2" />
    </p>
    <p>
      Click this button to create a generic Exception.<br />
      Application_Error will catch this and handle the error.<br />
      <asp:Button ID="Submit3" runat="server" 
        CommandArgument="3" OnClick="Submit_Click"
        Text="Button 3" />
    </p>
    <p>
      Click this button to create an HTTP 404 (not found) error.<br />
      Application_Error will catch this 
      and redirect to HttpErrorPage.aspx.<br />
      <asp:Button ID="Submit4" runat="server" 
      CommandArgument="4" OnClick="Submit_Click"
        Text="Button 4" />
    </p>
    <p>
      Click this button to create an HTTP 404 (not found) error.<br />
      Application_Error will catch this 
      but will not take any action on it, and ASP.NET
      will redirect to Http404ErrorPage.aspx. 
      The original exception object will not be
      available.<br />
      <asp:Button ID="Submit5" runat="server" 
        CommandArgument="5" OnClick="Submit_Click"
        Text="Button 5" />
    </p>
    <p>
      Click this button to create an HTTP 400 (invalid url) error.<br />
      Application_Error will catch this 
      but will not take any action on it, and ASP.NET
      will redirect to DefaultRedirectErrorPage.aspx. 
      The original exception object will not
      be available.<br />
      <asp:Button ID="Button1" runat="server" 
        CommandArgument="6" OnClick="Submit_Click"
        Text="Button 6" />
    </p>
  </div>
  </form>
</body>
</html>


GenericErrorPage.aspx

The following example shows the GenericErrorPage.aspx page. This page creates a safe message that it displays to remote users. For local users (typically developers and testers of the application), the page displays a complete exception report. The Page_Error handler redirects InvalidOperationException errors to this page.


<%@ Page Language="C#" %>

<script runat="server">
  protected Exception ex = null;

  protected void Page_Load(object sender, EventArgs e)
  {
    // Get the last error from the server
    Exception ex = Server.GetLastError();

    // Create a safe message
    string safeMsg = "A problem has occurred in the web site. ";

    // Show Inner Exception fields for local access
    if (ex.InnerException != null)
    {
      innerTrace.Text = ex.InnerException.StackTrace;
      InnerErrorPanel.Visible = Request.IsLocal;
      innerMessage.Text = ex.InnerException.Message;
    }
    // Show Trace for local access
    if (Request.IsLocal)
      exTrace.Visible = true;
    else
      ex = new Exception(safeMsg, ex);

    // Fill the page fields
    exMessage.Text = ex.Message;
    exTrace.Text = ex.StackTrace;

    // Log the exception and notify system operators
    ExceptionUtility.LogException(ex, "Generic Error Page");
    ExceptionUtility.NotifySystemOps(ex);

    // Clear the error from the server
    Server.ClearError();
  }
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head id="Head1" runat="server">
  <title>Generic Error Page</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <h2>
      Generic Error Page</h2>
    <asp:Panel ID="InnerErrorPanel" runat="server" Visible="false">
      <p>
        Inner Error Message:<br />
        <asp:Label ID="innerMessage" runat="server" Font-Bold="true" 
          Font-Size="Large" /><br />
      </p>
      <pre>
        <asp:Label ID="innerTrace" runat="server" />
      </pre>
    </asp:Panel>
    <p>
      Error Message:<br />
      <asp:Label ID="exMessage" runat="server" Font-Bold="true" 
        Font-Size="Large" />
    </p>
    <pre>
      <asp:Label ID="exTrace" runat="server" Visible="false" />
    </pre>
    <br />
    Return to the <a href='Default.aspx'> Default Page</a>
  </div>
  </form>
</body>
</html>


HttpErrorPage.aspx

The following example shows the HttpErrorPage.aspx page. This page also creates a safe message that depends on the value of the error code, which it displays to remote users. For local users, the page displays a complete exception report. The Application_Error handler redirects HttpException errors to this page.


<%@ Page Language="C#" %>

<script runat="server">
  protected HttpException ex = null;

  protected void Page_Load(object sender, EventArgs e)
  {
    ex = (HttpException)Server.GetLastError();
    int httpCode = ex.GetHttpCode();

    // Filter for Error Codes and set text
    if (httpCode >= 400 && httpCode < 500)
      ex = new HttpException
          (httpCode, "Safe message for 4xx HTTP codes.", ex);
    else if (httpCode > 499)
      ex = new HttpException
          (ex.ErrorCode, "Safe message for 5xx HTTP codes.", ex);
    else
      ex = new HttpException
          (httpCode, "Safe message for unexpected HTTP codes.", ex);

    // Log the exception and notify system operators
    ExceptionUtility.LogException(ex, "HttpErrorPage");
    ExceptionUtility.NotifySystemOps(ex);

    // Fill the page fields
    exMessage.Text = ex.Message;
    exTrace.Text = ex.StackTrace;

    // Show Inner Exception fields for local access
    if (ex.InnerException != null)
    {
      innerTrace.Text = ex.InnerException.StackTrace;
      InnerErrorPanel.Visible = Request.IsLocal;
      innerMessage.Text = string.Format("HTTP {0}: {1}",
        httpCode, ex.InnerException.Message);
    }
    // Show Trace for local access
    exTrace.Visible = Request.IsLocal;

    // Clear the error from the server
    Server.ClearError();
  }
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head id="Head1" runat="server">
  <title>Http Error Page</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <h2>
      Http Error Page</h2>
    <asp:Panel ID="InnerErrorPanel" runat="server" Visible="false">
      <asp:Label ID="innerMessage" runat="server" Font-Bold="true" 
        Font-Size="Large" /><br />
      <pre>
        <asp:Label ID="innerTrace" runat="server" />
      </pre>
    </asp:Panel>
    Error Message:<br />
    <asp:Label ID="exMessage" runat="server" Font-Bold="true" 
      Font-Size="Large" />
    <pre>
      <asp:Label ID="exTrace" runat="server" Visible="false" />
    </pre>
    <br />
    Return to the <a href='Default.aspx'>Default Page</a>
  </div>
  </form>
</body>
</html>


Http404ErrorPage.aspx

The following example shows the Http404ErrorPage.aspx page. ASP.NET redirects unhandled HTTP 404 (file not found) errors to this page. The page displays the same message to remote and local users.


<%@ Page Language="C#" %>

<script runat="server">
  protected HttpException ex = null;

  protected void Page_Load(object sender, EventArgs e)
  {
    // Log the exception and notify system operators
    ex = new HttpException("HTTP 404");
    ExceptionUtility.LogException(ex, "Caught in Http404ErrorPage");
    ExceptionUtility.NotifySystemOps(ex);
  }
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head id="Head1" runat="server">
  <title>HTTP 404 Error Page</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <h2>
      HTTP 404 Error Page</h2>
    Standard error message suitable for file not found errors. 
    The original exception object is not available, 
    but the original requested URL is in the query string.<br />
    <br />
    Return to the <a href='Default.aspx'> Default Page</a>
  </div>
  </form>
</body>
</html>


DefaultRedirectErrorPage.aspx

The following example shows the DefaultRedirectErrorPage.aspx page. ASP.NET redirects any unhandled errors except HTTP 404 errors to this page. The page displays the same message to remote and local users.


<%@ Page Language="C#" %>

<script runat="server">
  protected HttpException ex = null;

  protected void Page_Load(object sender, EventArgs e)
  {
    // Log the exception and notify system operators
    ex = new HttpException("defaultRedirect");
    ExceptionUtility.LogException(ex, "Caught in DefaultRedirectErrorPage");
    ExceptionUtility.NotifySystemOps(ex);
  }
</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head id="Head1" runat="server">
  <title>DefaultRedirect Error Page</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <h2>
      DefaultRedirect Error Page</h2>
    Standard error message suitable for all unhandled errors. 
    The original exception object is not available.<br />
    <br />
    Return to the <a href='Default.aspx'> Default Page</a>
  </div>
  </form>
</body>
</html>


Community Additions

ADD
Show:
© 2014 Microsoft