Monday, February 7, 2011

How to create custom error reporting pages in ASP.NET by using Visual C# .NET

This article describes how to use Visual C# .NET code to trap and respond to errors when they occur in ASP.NET. ASP.NET has improved the error handling options from traditional Microsoft Active Server Pages (ASP). In ASP.NET, you can handle errors at several different levels in your applications.

New features in ASP.NET

ASP.NET offers several advances in how you can handle and respond to errors. In traditional ASP, you handle errors with "On Error Resume Next" (or try-catch blocks in JScript). Alternately, if you are running Microsoft Internet Information Services (IIS) 5.0, you use the ASPError object to create a custom error reporting page. However, these approaches have their limitations.

ASP.NET provides several levels at which you can handle and respond to errors that may occur when you run an ASP.NET application. ASP.NET provides three main methods that allow you to trap and respond to errors when they occur: Page_Error, Application_Error, and the application configuration file (Web.config).

This article demonstrates how to use these new features in your ASP.NET application. Although this article describes how to provide custom error pages and general error reporting as it relates directly to ASP.NET, this article does not describe other error handling approaches such as the try-catch-finally block and the Common Language Runtime (CLR) exception system.

How to use the Page_Error method

The Page_Error event handler provides a way to trap errors that occur at the page level. You can simply display error information (as the sample code to follow does), or you can log the event or perform some other action.

Note This example displays detailed error information in the browser only for demonstration purposes. You will want to be cautious when displaying detailed information to the end user of the application, especially when the application is running on the Internet. A more appropriate action would be to display a message to the user notifying them that an error has occurred, and then actually logging the specific error details in the event log.

This example throws a null exception, which forces an error to occur in the Page_Load event handler. Follow these steps to create the initial page that will demonstrate using the Page_Error event handler.
  1. Follow these steps to add a new file named PageEvent.aspx to your project:
    1. Open Microsoft Visual Studio .NET.
    2. In Solution Explorer, right-click the project node, point to Add, and then click Add Web Form.
    3. In the Name text box, type PageEvent.aspx, and then click Open.
  2. Add the following code to PageEvent.aspx:
    <script language=C# runat="server">
    void Page_Load(object sender, System.EventArgs e)
    throw(new ArgumentNullException());

    public void Page_Error(object sender,EventArgs e)
    Exception objErr = Server.GetLastError().GetBaseException();
    string err = "<b>Error Caught in Page_Error event</b><hr><br>" +
    "<br><b>Error in: </b>" + Request.Url.ToString() +
    "<br><b>Error Message: </b>" + objErr.Message.ToString()+
    "<br><b>Stack Trace:</b><br>" +

    Note In this code sample, the AutoEventWireup attribute is not explicitly set. If you do not explicitly assign a value to the AutoEventWireup attribute, the default value true is used. If you are using Visual Studio .NET to develop your applications, the Web Form template code explicitly sets the AutoEventWireup attribute value to false. There is an important difference between the default value that ASP.NET uses, and the default value that the Visual Studio .NET template code assigns to this attribute. If the AutoEventWireup attribute value is set to false, the event handlers that are declared in the .ASPX page do not fire. This may be confusing if you do not know about this functionality.
  3. From the File menu, click Save PageEvent.aspx.
  4. Right-click the page, and then click View in Browser to run the page. Notice that the error is thrown and reported according to the code specifications.
Note You may notice that the code issues a call to Server.ClearError. This prevents the error from continuing to the Application_Error event handler.

In addition, you should also take note of the Inherits attribute in the @ Page directive. If Inherits is set, you must build the project before you browse to the page. If you do not build the project first, you receive the following error message:
'Project.PageEvent' is not a valid type

How to use the Application_Error method

Similar to the Page_Error event handler, you can use the Application_Error event handler to trap errors that occur in your application. Due to the event's application-wide scope, you can log of application error information or handle other application-level errors that may occur.

The sample to follow is based on the preceding Page_Error code sample and would be fired if the error in Page_Load was not trapped in the Page_Error event handler. The Application_Error event handler is specified in the Global.asax file of your application. For simplicity, the steps in this section create a new page in which to throw the exception, trap the error in the Application_Error event handler of the Global.asax file, and write the error to the event log. The following steps demonstrate how to use the Application_Error method:
  1. Add a new file named AppEvent.aspx to your project.
  2. Add the following code to AppEvent.aspx:
    <script language=C# runat="server">
    void Page_Load(object sender, System.EventArgs e)
    throw(new ArgumentNullException());

    Note The information discussed in the "Page_Error" section about the AutoEventWireup attribute also applies to the code sample in this step. See the information in the "Page_Error" section for more details.
  3. From the File menu, click Save AppEvent.aspx.
  4. Add the Application_Error event handler to the Global.asax file to trap the error that you throw in the Page_Load event handler of the AppEvent.aspx page. Notice that you must add another using statement for the System.Diagnostics namespace to Global.asax to use the event log.

    Add the following code to the Global.asax file:
    using System.Diagnostics;

    protected void Application_Error(object sender, EventArgs e)
    Exception objErr = Server.GetLastError().GetBaseException();
    string err = "Error Caught in Application_Error event\n" +
    "Error in: " + Request.Url.ToString() +
    "\nError Message:" + objErr.Message.ToString()+
    "\nStack Trace:" + objErr.StackTrace.ToString();
    //additional actions...
  5. Save the Global.asax file.
  6. In Visual Studio .NET, on the Build menu, click Build.
  7. Right-click the page, and then click View in Browser. In this case the page will be blank, however, you should notice that a new entry has been added in the event log. This sample makes an entry in the Application log, which is accessible from the Event Viewer. After logging the error you might want to redirect the user to another more user-friendly error page, or perform some additional actions if needed.