Compartir a través de


How to: Handle Application-Level Errors

This code example shows how to create an error handler in the Global.asax file that will catch all unhandled ASP.NET errors while processing a request — in other words, all the errors that are not caught with a Try/Catch block or in a page-level error handler. In the example, the handler transfers control to a generic error page named GenericErrorPage.aspx, which interprets the error and displays an appropriate message.

Example

The following example is from a complete code sample in Complete Example for Error Handlers.

Security noteSecurity Note:

Never set customErrors to Off in your Web.config file if you do not have an Application_Error handler in your Global.asax file. Potentially compromising information about your Web site can be exposed to anyone who can cause an error to occur on your site.

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
  ' Code that runs when an unhandled error occurs

  ' Get the exception object.
  Dim exc As Exception = Server.GetLastError

  ' Handle HTTP errors (avoid trapping HttpUnhandledException
  ' which is generated when a non-HTTP exception 
  ' such as the ones generated by buttons 1-3 in 
  ' Default.aspx is not handled at the page level).
  If (exc.GetType Is GetType(HttpException)) Then
    ' 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") Or exc.Message.Contains("maxUrlLength") Then
              Return
          End If

    'Redirect HTTP errors to HttpError page
    Server.Transfer("HttpErrorPage.aspx")
  End If

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

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

  ' Clear the error from the server
  Server.ClearError()
End Sub
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();
}

Robust Programming

An error handler that is defined in the Global.asax file will only catch errors that occur during processing of requests by the ASP.NET runtime. For example, it will catch the error if a user requests an .aspx file that does not occur in your application. However, it does not catch the error if a user requests a nonexistent .htm file. For non-ASP.NET errors, you can create a custom handler in Internet Information Services (IIS). The custom handler will also not be called for server-level errors.

You cannot directly output error information for requests from the Global.asax file; you must transfer control to another page, typically a Web Forms page. When transferring control to another page, use Transfer method. This preserves the current context so that you can get error information from the GetLastError method.

After handling an error, you must clear it by calling the ClearError method of the Server object (HttpServerUtility class).

Security

Be sure that you do not display error information that might help malicious users compromise your application. For details, see How to: Display Safe Error Messages.

See Also

Tasks

How to: Handle Page-Level Errors

Concepts

Complete Example for Error Handlers

Other Resources

Rich Custom Error Handling with ASP.NET

Change History

Date

History

Reason

April 2009

Added missing code example.

Content bug fix.