Recipe 8.3. Handling Errors at the Page Level


Problem

You want to trap any error that occurs on a page and, 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.

Examples 8-3 (VB) and 8-4 (C#) demonstrate 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. 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, etc. See Recipe 8.3 for an example of writing to the event log.

ASP.NET provides you with the ability to redirect the user to another page when an error occurs. To use this feature, set the ErrorPage property of the Page object to the URL of the page you want the user to see. You can add querystring parameters to the URL to pass specific error messages to the page. For instance, in the code snippets shown next, we've added three querystring parameters to the URL of an error message page: PageHeader, Message1, and Message2. PageHeader is set to the message "Error Occurred." Message1 is set to the message in the lastError exception. This will be the message from the last exception thrown. Message2 is a message we've added to say where the error was processed.

 

Page.ErrorPage = "CH08DisplayErrorVB.aspx" &_ "?PageHeader=Error Occurred" &_ "&Message1=" & lastError.Message &_ "&Message2=" &_ "This error was processed at the page level"

Page.ErrorPage = "CH08DisplayErrorCS.aspx" + "?PageHeader=Error Occurred" + "&Message1=" + lastError.Message + "&Message2=" + "This error was processed at the page level";

When the Page_Error event is completed, ASP.NET will automatically perform a redirect to the URL named in the ErrorPage property. You could do this yourself using Response.Redirect([Page URL]), but why write a line of code when ASP.NET can do it for you?

If you do not add any querystring parameters, ASP.NET will append one for you. The name of the parameter will be aspxerrorpath, and the value will be the relative URL to the specified page. In our example, the ASP.NET-added querystring would have been as follows:

 aspxerrorpath=/ASPNetCookbook2VB/CH08PageLevelErrorHandlingVB.aspx 


This technique, when coupled with those for handling exceptions at the method level (described in Recipe 8.1) can simplify handling errors in pages. The only place any code is required to gather error information and redirect to another page is in the Page_Error event handler. This is a significant improvement over the error-handling code required in classic ASP, where exception handling could be done only at the method level.

By default, ASP.NET displays the full error context in a special ASP.NET page on the local machine. If you access this example from a browser on the web server, the redirection described here will not occur. If you access this example from a different machine, the redirection will be performed. Refer to Chapter 12 when changing the default handling of error messages in web.config.


See Also

Recipes 8.1 and 8.3, Chapter 12

Example 8-3. Handling errors at the page level (.vb)

 Option Explicit On Option Strict On Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH08PageLevelErrorHandlingVB.aspx ''' </summary> Partial Class CH08PageLevelErrorHandlingVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _   ByVal e As System.EventArgs) Handles Me.Load Dim values As Hashtable = Nothing 'add a key/value pair to the hashtable without first creating 'the hashtable which will cause a null reference exception error values.Add("Key", "Value") End Sub 'Page_Load '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page error event. ''' It builds a URL with the error information then sets the ErrorPage ''' property to the URL. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub Page_Error(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Error Dim lastError As Exception 'get the last error that occurred lastError = Server.GetLastError( ) 'do any logging, notifications, etc. here 'set the URL of the page that will display the error and 'include querystring parameters to allow the page to display 'what happened Page.ErrorPage = "CH08DisplayErrorVB.aspx" &_  "?PageHeader=Error Occurred" &_  "&Message1=" &lastError.Message &_  "&Message2=" &_  "This error was processed at the page level" End Sub 'Page_Error End Class 'CH08PageLevelErrorHandlingVB End Namespace 

Example 8-4. Handling errors at the page level (.cs)

 using System; using System.Collections; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH08PageLevelErrorHandlingCS.aspx /// </summary> public partial class CH08PageLevelErrorHandlingCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { Hashtable values = null; // add a key/value pair to the hashtable without first creating // the hashtable which will cause a null reference exception error values.Add("Key", "Value"); } // Page_Load ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page error event. /// It builds a URL with the error information then sets the ErrorPage /// property to the URL. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> private void Page_Error(Object sender, System.EventArgs e) { Exception lastError = null; // get the last error that occurred lastError = Server.GetLastError( ); // do any logging, notifications, etc. here // set the URL of the page that will display the error and // include querystring parameters to allow the page to display // what happened Page.ErrorPage = "CH08DisplayErrorCS.aspx" +  "?PageHeader=Error Occurred" +  "&Message1=" + lastError.Message +  "&Message2=" +  "This error was processed at the page level";  } // Page_Error } // CH08PageLevelErrorHandlingCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net