Managing Unhandled Exceptions

The unhandled exceptions are those exceptions that are not caught in a try - catch block (inline coding) in an application. Whenever an unhandled exception occurs, ASP.NET displays its default error page to the user . The default error page can provide error details, along with code that can be a major security concern. You're usually better off displaying your own custom error messages instead.

ASP.NET stops processing the Web page after it encounters an unhandled exception. However, you can trap an unhandled exception at an object level, such as Page or Application .

Using Custom Error Pages

ASP.NET provides full built-in support for configuring custom error pages in a Web application. This configuration information is stored in an XML-based configuration file ( web.config ) where you use the <customErrors> element to configure custom error pages. The <customErrors> element consists of two attributes mode and defaultRedirect . The mode attribute specifies how the custom error pages should be displayed and can have one of the following three values:

  • On Displays custom error pages at both the local and remote clients .

  • Off Disables custom error pages at both the local and remote clients.

  • RemoteOnly Displays custom error pages only at remote clients. For the local machine, it displays the default ASP.NET error pages. This is the default setting in the web.config file.

The defaultRedirect attribute is an optional attribute that specifies the custom error page to be displayed when an error occurs. You can display either a static page, such as HTML, or a dynamic page, such as ASPX, as a custom error page. When the defaultRedirect attribute is not set to a custom error page, ASP.NET displays a generic error message in the browser.

A specific custom error page can be displayed for a specific HTTP error code by associating the error code with the Web page through the <error> element. Multiple <error> elements can be nested inside the <customErrors> element. The <error> element consist of the following two attributes:

  • statusCode HTTP error status code. For example: 403 (Forbidden), 404 (Not Found), 500 (Internal Server Error), and so on.

  • redirect The error page to which the browser should be redirected when the associated HTTP error occurs.

If an error occurs that has no specific page assigned through the <error> element, the custom error page specified by the defaultRedirect attribute of the <customErrors> element is displayed.

graphics/alert_icon.gif

An alternative way of configuring custom error pages is through Internet Information Services (IIS). When given a choice between IIS and ASP.NET custom error pages, you might prefer ASP.NET because in ASP.NET the custom pages are configured in an XML-based web.config (application configuration) file, resulting in easy ( xcopy ) deployment and management.


The following example shows how to set custom error pages for a Web application in the web.config file:

  1. Open the web.config file of your project from the Solution Explorer. Search for the <customErrors> element in the file and modify it with the following code in the file:

     <customErrors mode="On"    defaultRedirect="ApplicationError.htm">     <error statusCode="403" redirect="Forbidden.htm" />     <error statusCode="404" redirect="NotFound.htm" /> </customErrors> 
  2. Add a new HTML page, called ApplicationError.htm , to your project. Switch to HTML view and modify it with the following HTML code:

     <HTML>     <HEAD>         <TITLE>Application Error</TITLE>     </HEAD>     <BODY>         <H1>Application Error</H1>         <P>Sorry, there is a server application error.</P>     </BODY> </HTML> 
  3. Add a new HTML page, called Forbidden.htm , to your project. Switch to HTML view and modify it with the following HTML code:

     <HTML>     <HEAD><TITLE>Page Forbidden</TITLE></HEAD>     <BODY>         <H1>Page Forbidden</H1>         <P>Sorry, this page is forbidden.</P>     </BODY> </HTML> 
  4. Add a new HTML page, called NotFound.htm , to your project. Switch to HTML view and modify it with the following HTML code:

     <HTML>     <HEAD><TITLE>Page Not Found</TITLE></HEAD>     <BODY>         <H1>Page Not Found</H1>         <P>Sorry we don't have the page you requested.</P>     </BODY> </HTML> 
  5. Open the Example5_1.aspx file in code view. Comment the catch blocks in the btnCalculate_Click event handler so that exceptions are unhandled.

  6. Set Example5_1.aspx as the start page for the project.

  7. Run the project, enter invalid values for miles and gallons, and click the Calculate button. The Web page Example5_1.aspx comments the catch block and hence has no inline coding to handle exceptions. Therefore, it throws an unhandled exception and the ApplicationError.htm page is displayed.

  8. Now try displaying the code-behind file of Example5_1.aspx by typing http://localhost/ExamCram/315C05/Example5_1.aspx.cs . You should see that the Forbidden.htm page is displayed.

  9. Now, try displaying a nonexistent page in the Web application. Say that you make a mistake by typing a hyphen instead of an underscore symbol, such as http://localhost/ExamCram/315C05/Example5-1.aspx . Notice that the NotFound.htm page is displayed. The custom error page is displayed only if the not found page is one that would have been processed by ASP.NET. For example, if you tried to get to Example5-1.htm , you wouldn't see the custom error page because IIS would never call ASP.NET to process the request of the HTML page.

  10. Repeat steps 79 after changing the value of the mode attribute (of the <customErrors> element in the web.config file) to Off (where no custom error pages will be displayed) and then RemoteOnly (where custom error pages will be displayed on remote machines and default errors on the local machine).

graphics/note_icon.gif

Sometimes a particular Web page in an application might want to display its own error page. This can be done by setting the ErrorPage attribute of the Page directive or the ErrorPage property of the Page class to the desired custom error page. You would use this code:

<%@ Page language="C#" ErrorPage=" SpecificErrorPage.htm "%>

When the custom error page is set using this technique, it overwrites the settings that apply to this Web page via the web.config file.


Using Error Events

When an unhandled exception occurs in a Web application, the following events are fired in successive order:

  1. Page.Error , which is a page-level event handled by the Page_Error() event handler

  2. Application.Error , which is an application-level event handled by the Application_Error() event handler

Both of these event handlers can be used to trap and work with unhandled exceptions.

Using the Page.Erro Event

The Page_Error() event handler can be used to trap unhandled exceptions at a page level, like so:

 private void Page_Error(object sender, System.EventArgs e) {     Response.Write("Error Details: <br>");     // Display error details. Get the last error on the Server     Response.Write(Server.GetLastError().Message + "<br>");     Response.Write(Server.GetLastError().StackTrace + "<br>");     // Clear the error to flush the new response     // and erase the default ASP.NET error page     Server.ClearError(); } 

The preceding Page_Error() event handler displays the details of the unhandled exception. This is achieved by calling the HttpServerUtility object's GetLastError() method via the Server property. The method returns an Exception object that provides a reference to the last exception that occurred on the server.

The ClearError() method of the HttpServerUtility object clears the last exception and does not fire subsequent error events (for example, Application.Error ) for the exception. For this reason, you will notice that the custom error page is not displayed even though an unhandled error exists. Also for the same reason, the default ASP.NET error page is not displayed if no custom error page is configured.

Using the Application.Error Event

You can also choose to trap unhandled exceptions of the entire application in the Application.Error event. This event is handled by the Application_Error() event handler available in the ASP.NET application file, global.asax . Handling exceptions at the application level can be helpful when you want to take custom actions, such as logging the exception- related information in the event log for all Web pages, like so:

 protected void Application_Error(Object sender, EventArgs e) {   // Get the Exception object wrapped in the InnerException property     Exception unhandledException =       (Exception)Server.GetLastError().InnerException;     //If no event source exists, create an event source     if(!EventLog.SourceExists("Mileage Efficiency Calculator"))         EventLog.CreateEventSource("Mileage Efficiency Calculator",           "Mileage Efficiency Calculator Log");     // Create an EventLog instance and assign its source.     EventLog eventLog = new EventLog();     eventLog.Source = "Mileage Efficiency Calculator";     string type= unhandledException.Message;     // Write an informational entry to the event log.     eventLog.WriteEntry(unhandledException.Message);     Response.Write("An exception occurred: " +         "Created an entry in the event log.");     Server.ClearError(); } 

When ASP.NET propagates the unhandled exception to the Application object (the Application.Error event), the Exception object is wrapped in an HttpUnhandledException object. Therefore, to access the exception at the application level, you must access the Exception object's InnerException property.

If the Page_Error() event handler does not clear the unhandled exception through the ClearError() method, both the Page.Error and Application.Error events are fired. Further, if the Application_Error() event handler does not clear the exception, the error page (custom, if configured) is displayed in the browser. This happens because the error is not cleared although the event handlers for the Page.Error and Application.Error events are executed.



MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
ISBN: 789729016
EAN: N/A
Year: 2005
Pages: 191

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