O'Reilly logo

ASP.NET Cookbook 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

7.2. Handling Errors at the Page Level

Problem

You want to trap any error that occurs on a page and then, using a page-level event handler, redirect the user to another page that displays the information about the problem.

Solution

Add code to the Page_Error event handler of the page to set the ErrorPage property of that page to the URL you want to display to the user when an error occurs.

In the code-behind for the page, use the .NET language of your choice to:

  1. Add a Page_Error event handler.

  2. In the event handler, get a reference to the last error that occurred using the GetLastError method.

  3. Set the ErrorPage property of the Page object to the URL of the page you want displayed after the error, adding querystring parameters to pass error information to the page.

Example 7-3 (VB) and Example 7-4 (C#) show an example that demonstrates this solution. (Because the .aspx file for this example contains nothing related to the error handling, it is not included here.)

Discussion

The Page_Error event of the ASP.NET Page object is raised any time an unhandled error occurs in a page. In C#, be sure to wire the Page_Error method to the page error event. This can be done in the InitializeComponent method or the Page_Load method with the following line of code:

               this.Error += new System.EventHandler(this.Page_Error);

The first action required in the event handler is to get a reference to the last error. After getting the reference, the code should perform the required logging, notifications, and the ...

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