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.
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:
Add a Page_Error
event handler.
In the event handler, get a reference to the last error that occurred
using
the GetLastError
method.
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.)
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 like. See Recipe 7.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, simply 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 simply 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 = "CH07DisplayErrorVB.aspx" & _"?PageHeader=Error Occurred" & _
"&Message1=" & lastError.Message & _
"&Message2=" & _
"This error was processed at the page level"
Page.ErrorPage = "CH07DisplayErrorCS.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=/aspnetcookbook/VBExamples/CH07PageLevelErrorHandlingVB.aspx
This technique, when coupled with those for handling exceptions at
the method level (described in Recipe 7.1)
can greatly 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 that was
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 9 for changing the default handling of error
messages in web.config
.
Recipe 7.1; Recipe 7.3
Example 7-3. Handling errors at the page level (.vb)
Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: CH07PageLevelErrorHandlingVB.aspx.vb ' ' Description: This module provides the code behind for ' CH07PageLevelErrorHandlingVB.aspx ' '***************************************************************************** Imports System Imports System.Collections Namespace ASPNetCookbook.VBExamples Public Class CH07PageLevelErrorHandlingVB Inherits System.Web.UI.Page '************************************************************************* ' ' ROUTINE: Page_Load ' ' DESCRIPTION: This routine provides the event handler for the page load ' event. It is responsible for initializing the controls ' on the page. '------------------------------------------------------------------------- Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim values As Hashtable'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 '************************************************************************* ' ' ROUTINE: Page_Error ' ' DESCRIPTION: 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. '-------------------------------------------------------------------------Private Sub Page_Error(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.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 = "CH07DisplayErrorVB.aspx" & _
"?PageHeader=Error Occurred" & _
"&Message1=" & lastError.Message & _
"&Message2=" & _
"This error was processed at the page level"
End Sub 'Page_Error
End Class 'CH07PageLevelErrorHandlingVB End Namespace
Example 7-4. Handling errors at the page level (.cs)
//---------------------------------------------------------------------------- // // Module Name: CH07PageLevelErrorHandlingCS.aspx.cs // // Description: This module provides the code behind for // CH07PageLevelErrorHandlingCS.aspx // //**************************************************************************** using System; using System.Collections; namespace ASPNetCookbook.CSExamples { public class CH07PageLevelErrorHandlingCS : System.Web.UI.Page { //************************************************************************ // // ROUTINE: Page_Load // // DESCRIPTION: This routine provides the event handler for the page // load event. It is responsible for initializing the // controls on the page. //------------------------------------------------------------------------ private void Page_Load(object sender, System.EventArgs e) { Hashtable values = null; // wire the page error event this.Error += new System.EventHandler(this.Page_Error);// 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 //************************************************************************ // // ROUTINE: Page_Error // // DESCRIPTION: 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. //------------------------------------------------------------------------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 = "CH07DisplayErrorCS.aspx" +
"?PageHeader=Error Occurred" +
"&Message1=" + lastError.Message +
"&Message2=" +
"This error was processed at the page level";
} // Page_Error
} // CH07PageLevelErrorHandlingCS }