JavaScript Editor jscript editor     Web designer 



Main Page

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 of 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 Errors.aspx, which interprets the error and displays an appropriate message.

Example

Visual BasicВ CopyCode imageCopy Code
' Handler in Global.asax file
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    Server.Transfer("Errors.aspx")
End Sub

' Handler in Errors.aspx file
Private Sub Page_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
    Dim errMessage As System.Text.StringBuilder = _
        New System.Text.StringBuilder()
    Dim appException As System.Exception = Server.GetLastError()
    If (TypeOf (appException) Is HttpException) Then
        Dim checkException As HttpException = _
            CType(appException, HttpException)
        Select Case checkException.GetHttpCode
        Case 403
            errMessage.Append( _
                "You are not allowed to view that page.")
        Case 404
            errMessage.Append( _
                "The page you requested cannot be found.")
        Case 408
            errMessage.Append( _
                "The request has timed out.")
        Case 500
            errMessage.Append( _
              "The server cannot fulfill your request.")
        Case Else
            errMessage.Append( _ 
              "The server has experienced an error.")
        End Select
    Else
        ' The exception was not an HttpException.
        errMessage.AppendFormat( _
          "The following error occurred<br />{0}", _
              appException.ToString
    End If
    errMessage.Append("<br />Please contact the server administrator.")
    Label1.Text = errMessage.ToString()
    Server.ClearError()
End Sub
  // Handler in Global.asax file
  void Application_Error(Object sender, EventArgs e) {
    Server.Transfer("Errors.aspx");
  }

  // Handler in Errors.aspx file.
  protected void Page_Load(object sender, EventArgs e)
  {
    System.Text.StringBuilder errMessage = new StringBuilder();
    System.Exception appException = Server.GetLastError();

    if (appException is HttpException)
    {
      HttpException checkException = (HttpException)appException;
      switch (checkException.GetHttpCode())
      {
        case 403:
          {
            errMessage.Append("You are not allowed to view that page.");
            break;
          }
        case 404:
          {
            errMessage.Append("The page you requested cannot be found.");
            break;
          }
        case 408:
          {
            errMessage.Append("The request has timed out");
            break;
          }
        case 500:
          {
            errMessage.Append("The server cannot fullfill your request.");
            break;
          }
        default:
          {
            errMessage.Append("Ther server has experienced an error.");
            break;
          }

      }
    }
    else
    {
      // The exception was not an HttpException.
      errMessage.AppendFormat("The following error occurred<br />{0}",
        appException.ToString());
    }

    errMessage.Append("<br />Please contact the server administrator.");
    Label1.Text = errMessage.ToString();

    Server.ClearError();
  }

Compiling the Code

This code example requires:

  • A Web application.

  • A Web Forms page called Errors.aspx that contains a Label control called Label1.

Robust Programming

It is preferable to use Try/Catch blocks around any code that is subject to errors rather than rely on a global error handler.

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 exist 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 also will 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

Other Resources

How to: Redirect to Another Page in the Same Application (Visual Basic)
Web Applications Example Topics (Visual C#)



JavaScript Editor jscript editor     Web designer