Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Custom Errors in ASP.NET

0.00/5 (No votes)
27 May 2002 1  
In this article I will talk about customizing the default error page, manipulating the configuration file and sending notification to the administrator about errors.

Introduction

Structured exception handling is a fundamental part of the CLR and provides .NET programmers with a great way of managing errors. In addition to the 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 it 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:

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

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

Customisation 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.

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.

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, customisation 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:

Description of the error can be viewed by selecting the appropriate event and double clicking it.

Another form pops up as shown below:

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:

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.ToString
        mail.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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here