ARTICLE

Custom Error Handling in ASP.NET

Posted by Amit Kukreja Articles | Exception Handling C# May 30, 2002
Structured exception handling is a fundamental part of the CLR and provides .Net programmers a great way of managing errors. In addition to CLR exception system, ASP.Net also provides ways of handling errors.
Reader Level:

Introduction

Structured exception handling is a fundamental part of the CLR and provides .Net programmers a great way of managing errors. In addition to CLR exception system, ASP.Net also provides ways of handling errors.

When a runtime or design-time error occurs in an application, ASP.Net shows a default error page that gives a brief description of the error along with the line number on which the error occurred. A developer would wish to view this default error page, during the testing of the application since the description helps him in rectifying the error. But he would never want a user trying to access his application, to view this error page. The user would be least bothered to know about the error. Instead of showing the default error page, it would be more sensible to show a customized error page that would let the user send notification of the error to the administrator.

Explanation

Consider an example of an ASP.Net application that generates an error intentionally to show how ASP.Net detects it and shows the default error page. The below given webform contains a label and a button server control. In the eventhandler for the button click event, the user will be redirected to another webform "Trial.aspx". Since the page being redirected to, is missing ASP.Net will show the default error page indicating it is a runtime error.

Unlike classic ASP, ASP.Net separates the code for the business logic from the content (i.e HTML and interface logic). The sample application has two files named "webform1.aspx" containing the content and "webform1.aspx.vb" containing the code.

WebForm1.aspx

<%@ Page Language="vb" AutoEventWireup="false"
Codebehind="WebForm1.aspx.vb" Inherits="ErrorSample.WebForm1"%>

<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN">
<
HTML
>
<HEAD
>
<title></title
>
<meta name="GENERATOR" content
="Microsoft Visual Studio.NET 7.0">
<meta name="CODE_LANGUAGE" content
="Visual Basic 7.0">
<meta name="vs_defaultClientScript" content
="JavaScript">
<meta name="vs_targetSchema" content
=
"http://schemas.microsoft.com/intellisense/ie5">
</HEAD
>
<body MS_POSITIONING
="GridLayout">
<form id="Form1" method="post" runat
="server">
<asp:Label id="Message" style
="Z-INDEX: 101; LEFT: 34px;
POSITION: absolute; TOP: 46px"
runat="server"></asp:Label
>
<asp:Button id="ErrorButton" style
="Z-INDEX: 102; LEFT: 268px;
POSITION: absolute; TOP: 41px"
runat="server" Text
="Generate
Error"></
asp:Button
>
</form
>
</body
>
</
HTML
>

WebForm1.aspx.vb

Public Class
WebForm1
Inherits
System.Web.UI.Page
Protected WithEvents Message As
System.Web.UI.WebControls.Label
Protected WithEvents ErrorButton As
System.Web.UI.WebControls.Button
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

Handles
MyBase.Load
Message.Text = "This sample page generates an Error..."
End
Sub
Public Sub ErrorButton_Click(ByVal sender As Object, ByVal e
As
System.EventArgs)
Handles
ErrorButton.Click
Response.Redirect("Trial.aspx")
End
Sub
End
Class

Now if you try to run the above web form by viewing it on the browser, you will get the below shown web page:

CustErrorHandfig3.gif

Now if you click on the button labeled "Generate Error", you will get the below shown default ASP.Net error page.

CustErrorHandfig5.gif

Customizing Error Page

To customize the default error page, one will have to change the default configuration settings of the application.

There are three error modes in which an ASP.Net application can work:

  1. Off Mode
  2. On Mode
  3. RemoteOnly Mode

The Error mode attribute determines whether or not an ASP.Net error message is displayed. By default, the mode value is set to "RemoteOnly".

  • Off Mode
    When the error attribute is set to "Off", ASP.Net uses its default error page for both local and remote users in case of an error.
  • On Mode
    In case of "On" Mode, ASP.Net uses user-defined custom error page instead of its default error page for both local and remote users. If a custom error page is not specified, ASP.Net shows the error page describing how to enable remote viewing of errors.
  • RemoteOnly
    ASP.Net error page is shown only to local users. Remote requests will first check the configuration settings for the custom error page or finally show an IIS error.

Configuration File

Customization of error page can be implemented by adding a value for an attribute "defaultRedirect" in the <customErrors> tag of the configuration file "web.config". This file determines configuration settings for the underlying application.

  • Off Mode
    In this scenario, set the mode attribute value to "Off" as shown below:

    Web.Config File

    <?xml version="1.0" encoding="utf-8"
    ?>
    <
    configuration
    >
    <system.web
    >
    <customErrors mode="Off"
    />
    </system.web
    >
    </
    configuration
    >

    When the sample ASP.Net web page is viewed in the browser from the remote machine, one gets the below shown default error page.

    CustErrorHandfig6.gif

    The above example thus shows that, whether it is local or remote access, ASP.Net error page is shown.

    On Mode

    In this scenario, set the mode attribute value to "On" as shown below:

    Web.Config File
    <?xml version="1.0" encoding="utf-8"
    ?>
    <
    configuration
    >
    <system.web
    >
    <customErrors defaultRedirect="error.htm" mode="On"
    />
    </system.web
    >
    </
    configuration
    >

    As shown in the configuration file, the "defaultRedirect" attribute has been set to a user-defined page "error.htm". The user-defined error page can be an ASP.Net web page, classic ASP page or a simple HTML page.

    For example, the contents of the user-defined error page "error.htm" can be given as follows:

    Error.htm

    <HTML
    >
    <
    BODY
    >
    <b
    >
    We are very sorry for the inconvenience caused to you...<br
    >
    </b
    >
    </
    BODY
    >
    </
    HTML
    >

    When the sample ASP.Net web page is viewed in the browser from the remote/local machine, one gets the below shown custom error page.

    CustErrorHandfig7.gif


  • RemoteOnly Mode

    In this scenario, set the mode attribute value to "RemoteOnly" as shown below:

    Web.Config File
    <?xml version="1.0" encoding="utf-8"
    ?>
    configuration
    >
    <system.web
    >
    <customErrors defaultRedirect="error.htm" mode="RemoteOnly"
    />
    </system.web
    >
    </
    configuration
    >

    Since the "defaultRedirect" attribute has been set, if the page is requested from a remote machine page is redirected to "error.htm" and if the page is requested from the local machine the default error page is shown.

Notification of Error to the Administrator

In a practical web application, customization of error pages is not the only requirement. The error, if encountered, should be reported to the administrator so that it can be rectified thus enabling subsequent requests to work properly without any error.

Notification of the error can be sent to the administrator in one of the following two ways:

  1. Error can be registered as a log entry in the Windows Event Log on the administrator's machine.
  2. An Email can be sent to the administrator with a suitable error message.
  • Writing to the Event Log

    In ASP.Net, error can be handled programmatically by writing appropriate code in the page-level error event, for errors on an individual page or in the application-level error event for handling errors that may occur in any page of the application.

    Therefore, code for writing in the Event Log should be written in either of the events, depending on the requirement of the application. To illustrate this example, I have written the code in the application-level event with the error mode set to "RemoteOnly" and the "defaultRedirect" attribute to "error.htm". The application-level error event should be included in the global file "global.asax" within the same application folder.

    The contents of the global file can be given as follows:

    Writing Log Entry in the Event Log

    Imports System.Web
    Imports System.Web.SessionState
    Imports System.Diagnostics
    Public Class Global
    Inherits System.Web.HttpApplication
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    Dim ErrorDescription As String = Server.GetLastError.ToString
    'Creation of event log if it does not exist
    Dim EventLogName As String = "ErrorSample"
    If (Not EventLog.SourceExists(EventLogName)) Then
    EventLog.CreateEventSource(EventLogName, EventLogName)
    End If
    ' Inserting into event log
    Dim Log As New EventLog
    Log.Source = EventLogName
    Log.WriteEntry(ErrorDescription, EventLogEntryType.Error)
    End Sub
    End
    Class

    Event Log support is provided in .Net through the namespace "System.Diagnostics". So, for the above code to work, it is very essential to add a reference to the above-mentioned namespace in the project. In the event handler for application-level error, a log named "ErrorSample" is created if it does not exist in the Event Log. If it already exists, the error entry is added to the existing list of events. After viewing the page on the browser from a remote machine, the event will get listed in the Event Log on the administrator's machine as shown below:

    CustErrorHandfig2.gif

    Description of the error can be viewed by selecting the appropriate event and double clicking it. Another form pops up as shown below:

    CustErrorHandfig8.gif

  • Sending an Email to the Administrator

    To illustrate this example, I have written the code for sending an Email to the administrator in the application-level error event. The contents of the global file can be given as follows:

    Sending Email To the Administrator

    Imports System.Web
    Imports System.Web.SessionState
    Imports System.Web.Mail
    Public Class Global
    Inherits System.Web.HttpApplication
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    Dim mail As New MailMessage
    Dim ErrorMessage = "The error description is as follows : "
    & Server.GetLastError.ToStringmail.To = administrator@domain.com
    mail.Subject = "Error in the Site"
    mail.Priority = MailPriority.High
    mail.BodyFormat = MailFormat.Text
    mail.Body = ErrorMessage
    SmtpMail.Send(mail)
    End Sub
    End
    Class

    In the above code, SMTP service is being used to send the mail across. SMTP mail service support is provided in .Net through the namespace "System.Web.Mail". So, for the above code to work, it is very essential to add a reference to the above-mentioned namespace in the project.

COMMENT USING
Employers - Post Free Jobs