Working with Custom Error Pages Using ASP.NET
page 3 of 7
by SANJIT SIL
Feedback
Average Rating: 
Views (Total / Last 10 Days): 59907/ 47

Sequence of Events

The actual order of error handling events is as follows.

Page_Error of .aspx file or associated codebehind

Application_Error in Global.ascx file

CustomErrors section of the application configuration files (Web.config)

Server.ClearError and Server.GetLastError

Two important server side methods named Server.ClearError and Server.GetLastError are used in the following code listing.  Here is a brief description of these two methods.

Server.ClearError: Use this method to handle the exception and stop the error to trigger the subsequent error event or display the error to the user.  If we do not clear the exception by using the Server.ClearError, the unhandled exception will continue to propagate up to the Application_Error event.  If we use Server.ClearError to clear the exception in Application_Error, the default redirect setting in the Web.config file will not redirect the user because the unhandled exception no longer exists.  If you want the default redirect setting to properly redirect users, do not clear the exception in Application_Error.

Server.GetLastError: A call to Server.GetLastError will return the most recent error.

Page_Error Method

ASP.NET provides as the 1st level of error handling by means of Page_Error event handler which provides a way to trap errors that occur at the page level in a web application.  The following example throws a divide by zero exception which forces an error to occur in the Page_Load event handler.  To demonstrate Page_Error event handler we have to create or add a new web form (say) named as PageError.aspx and then we should add the following code to PageError.aspx.

Listing 1

<script language=C# runat="server">
void Page_Load(object sender, System.EventArgs e)
{
      int i=0;
      int j=5;
      int k=0;
      k=j/k;
}
 
public void Page_Error(object sender,EventArgs e)
{
      Exception objError = Server.GetLastError().GetBaseException();
      string strError = "<b>Error Has Been Caught in Page_Error event</b><hr><br>" + 
                  "<br><b>Error in: </b>" + Request.Url.ToString() +
                  "<br><b>Error Message: </b>" + objError.Message.ToString()+
                  "<br><b>Stack Trace:</b><br>" + 
                        objError.StackTrace.ToString();
      Response.Write(strError.ToString());
      Server.ClearError();
}
</script> 

AutoEventWireup

The AutoEventWireup attribute may have a value of true or false.  When an ASP.NET Web Application is created by using Microsoft Visual Studio .NET, the value of the AutoEventWireup attribute is set as false.  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.  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.  To test the same you can write AutoEventWireup=”false” and then you will see that a white page is coming without showing the content of Figure1. 

Listing 2

<%@ Page language="c#"
 Codebehind="PageError.aspx.cs" AutoEventWireup="false"
 Inherits="CustomError.PageError" %>

After saving the page, when we run the application we will see that the error is thrown and reported according to the code specifications.  The following screen shot (see Figure 1) describes the error handled by the Page_Error event handler.

Figure 1


Application Error Method

Along with page level error handlers, ASP.NET gives developers the ability to provide application-level error handling.  The page-level error handling comes first, after ASP.NET calls the Page_Error procedure, and then ASP.NET calls the Application_Error procedure.  We can simply display error information, log the event to the Windows Event Log, send E-mail to system administrator or we can simply redirect to another page.

The Application_Error event handler is specified in the Global.asax file of our application.

Here a new page named ApplicationError.aspx is added and the following code is written in that page to generate the error.

Listing 3

<script language=C# runat="server">
  void Page_Load(object sender, System.EventArgs e)
  {
    int i=0;
    int j=5;
    int k=0;
    k=j/k;
  }
</script>

The AutoEventWireup attribute as discussed in the "Page_Error" section also applies to the code sample in this step.  To trap the error generated in the page load of ApplicationError.aspx using the above code listing we have to add the following code to the Global.asax file.

Add the following namespace to use the event log.

Listing 4

using System.Diagnostics;

Add the following code in Application_Error event to trap the error that will be thrown in the Page_Load event handler of the ApplicationError.aspx page.

Listing 5

public void Page_Error(object sender,EventArgs e)
{
      Exception objError = Server.GetLastError().GetBaseException();
      string strError = "<b>Error Has Been Caught in Page_Error event</b><hr><br>" + 
                  "<br><b>Error in: </b>" + Request.Url.ToString() +
                  "<br><b>Error Message: </b>" + objError.Message.ToString()+
                  "<br><b>Stack Trace:</b><br>" + 
                        objError.StackTrace.ToString();
      Response.Write(strError.ToString());
      Server.ClearError();
}
</script> 

If we right-click the page and then click View in the Browser, the page will be blank (i.e. white screen).  However, we 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.

In this function we can even save error information to session state and then perform the redirect manually.

Listing 6

protected void Application_Error(Object sender, EventArgs e)
{
  Exception objError = Server.GetLastError().GetBaseException();
  string strError = "Error Has Been Caught in Application_Error event\n" +
    "Error in: " + Request.Url.ToString() + "\nError Message:" +
    objError.Message.ToString() + "\nStack Trace:" +
    objError.StackTrace.ToString();
  Session["error"= strError.ToString();
  Server.Transfer("WebForm1.aspx");
 
}

Now, on the custom error page we will have access to all the information pertaining to the error.  We can then use this for error reporting via email to the developers/system admin or to display a more pleasing error message.


View Entire Article

User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 8:01:00 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search