O'Reilly logo

ASP.NET 2.0 Cookbook, 2nd Edition by Geoffrey T. LeBlond, Michael A Kittel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.3. Handling Errors at the Application Level

Problem

You want to report and log all errors in a common location, regardless of where they arise within the application.

Solution

Incorporate the error handling in methods (described in Recipe 8.1), add code to the Page_Error event handler to rethrow the page errors, and add the code to the Application_Error event handler to perform the logging and redirection.

In the code-behind class for your ASP.NET pages that need to perform error handling, use the .NET language of your choice to:

  1. Create a Page_Error event handler.

  2. Rethrow the page errors from within the method. (This is needed to avoid all errors being wrapped with an HttpUnhandledException exception.)

In global.asax, use the .NET language of your choice to:

  1. Create an Application_Error event handler.

  2. Create a detailed message and write it to the event log.

  3. Redirect the user to the error page using Server.Transfer.

The code we’ve written to demonstrate this solution is shown in Examples 8-6, 8-7, 8-8 through 8-9. The Page_Error code required in all pages is shown in Examples 8-6 (VB) and 8-7 (C#). The Application_Error code required in global.asax is shown in Examples 8-8 (VB) and 8-9 (C#). (Because the .aspx file for this example contains nothing related to the error handling, it is not included here.)

Discussion

The exception model in ASP.NET provides the ability for exceptions to be handled at any level, from the method level to the application level. An unhandled exception is sequentially ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required