Tuesday, June 23, 2009

Custom Error Pages In ASP.NET

This tutorial is part of series that covers error handling in ASP.NET. You can find additional information on:

* Errors And Exceptions In ASP.NET - covers different kinds of errors, try-catch blocks, introduces Exception object, throwing an exception and page_error procedure.
* Application Level Error Handling in ASP.NET - goes a level higher and explains handling of unhandled errors by using Application_Error procedure in Global.asax file, using of custom Http modules, sending notification e-mail to administrator, show different error pages based on roles and logging errors to text files, database or EventLog.

This tutorial deals with user experience when error occurs. When error is occurred on ASP.NET web application, user will get default error page (which is not so nice looking, also known as "Yellow screen of death"). This error page confuses average visitor who don't know the meaning of "Runtime Error". Although developers like to know many details about an error, it is better to show more friendly error page to your users.

Web.config file contains a customErrors section inside <System.web>. By default, this section looks like this:

<customErrors mode="RemoteOnly" />

As you see, there is mode parameter inside customErrors tag which value is "RemoteOnly". This means that detailed messages will be shown only if site is accessed through a http://localhost. Site visitors, who access from external computers will see other, more general message, like in image bellow:

Default ASP.NET error message
Default ASP.NET error message

mode parameter can have three possible values:

- RemoteOnly - this is default value, detailed messages are shown if you access through a localhost, and more general (default) error message to remote visitors.

- On - default error message is shown to everyone. This could be a security problem since part of source code where error occurred is shown too.

- Off - detailed error message is shown to everyone.

Default ASP.NET error message hides details about error, but still is not user friendly. Instead of this page, ASP.NET allows you to create your own error page. After custom error page is created, you need to add a reference to it in customErrors section by using a defaultRedirect parameter, like in code snippet bellow:

<customErrors mode="RemoteOnly" defaultRedirect="~/DefaultErrorPage.htm" />

When error occured, ASP.NET runtime will redirect visitor to DefaultErrorPage.htm. On custom error page you can gently inform your visitors what happened and what they can do about it.

DefaultErrorPage.htm will display when any error occurs. Also, there is a possibility to show different custom error pages for different types of exceptions. We can do that by using <error > sub tag. In code sample bellow, specialized pages are shown for errors 404 (File Not Found) and error 403 (Forbidden).

<customErrors mode="On" defaultRedirect="~/DefaultErrorPage.htm" >

<error statusCode="404" redirect="~/FileNotFound.htm"/>

<error statusCode="403" redirect="~/Forbidden.htm"/>

</customErrors>

How to set error page for every ASP.NET page

Custom pages configured in Web.config affect complete web site. It is possible also to set error page for every single ASP.NET page. We can do this by using @Page directive. Code could look like this:

<%@ Page language="C#" Codebehind="SomePage.aspx.cs" errorPage="MyCustomErrorPage.htm" AutoEventWireup="false"%>

Http Error page codes

There are different Http codes that your web application could return. Some errors are more often than others. You probably don't need to cover all cases. It is ok to place custom error pages for the most common error codes and place default error page for the rest.

400 Bad Request

Request is not recognized by server because of errors in syntax. Request should be changed with corrected syntax.

401 Not Authorized

This error happens when request doesn't contain authentication or authorization is refused because of bad credentials.

402 Payment Required

Not in use, it is just reserved for the future

403 Forbidden

Server refused to execute request, although it is in correct format. Server may or may not provide information why request is refused.

404 Not Found

Server can not find resource requested in URI. This is very common error, you should add custom error page for this code.

405 Method Not Allowed

There are different Http request methods, like POST, GET, HEAD, PUT, DELETE etc. that could be used by client. Web server can be configured to allow or disallow specific method. For example, if web site has static pages POST method could be disabled. There are many theoretical options but in reality this error usually occurs if POST method is not allowed.

406 Not Acceptable

Web client (browser or robot) could try to receive some data from web server. If that data are not acceptable web server will return this error. Error will not happen (or very rarely) when web browser request the page.

407 Proxy Authentication Required

This error could occur if web client accesses to web server through a proxy. If proxy authentication is required you must first login to proxy server and then navigate to wanted page. Because of that this error is similar to error 401 Not Authorized, except that here is problem with proxy authentication.

408 Request Timeout

If connection from web client and server is not established in some time period, which is defined on web server, then web server will drop connection and send error 408 Request Timeout. The reason could be usually temporarily problem with Internet connection or even to short time interval on web server.

409 Conflict

This error rarely occurs on web server. It means that web request from client is in conflict with some server or application rule on web server.

410 Gone

This error means that web server can't find requested URL. But, as opposed to error 404 Not Found which says: "That page is not existing", 410 says something like: "The page was here but not anymore". Depending of configuration of web server, after some time period server will change error message to 404 Not Found.

411 Length Required

This error is rare when web client is browser. Web server expects Content-Length parameter included in web request.

412 Precondition Failed

This is also rare error, especially if client is web browser. Error occurs if Precondition parameter is not valid for web server.

413 Request Entity Too Large

This error occurs when web request is to large. This is also very rare error, especially when request is sent by web browser.

414 Request URI Too Long

Similar like error 413, error occurs if URL in the web request is too long. This limit is usually 2048 to 4096 characters. If requested URL is longer than server's limit then this error is returned. 2048 characters is pretty much, so this error occurs rarely. If your web application produces this error, then it is possible that is something wrong with your URLs, especially if you build it dynamically with ASP.NET server side code.

415 Unsupported Media Type

This error occurs rarely, especially if request is sent by web browser. It could be three different reasons for this error. It is possible that requested media type doesn't match media type specified in request, or because of incapability to handle current data for the resource, or it is not compatible with requested Http method.

416 Requested Range Not Satisfied

This is very rare error. Client request can contain Range parameter. This parameter represents expected size of resource requested. For example, if client asks for an image, and range is between 0 and 2000, then image should not be larger from 2000 bytes. If image is larger, this error is returned. However, web page hyperlinks usually don't specify any Range value so this error rarely occurs.

417 Expectation Failed

This is also rare error, especially if client is web browser. There is Expect parameter of request, if this Expect is not satisfied Expectation error is returned.

500 Internal Server Error

This is very common error; client doesn't know what the problem is. Server only tells that there is some problem on server side. But, on the server side are usually more information provided. If server hosts ASP.NET application, then this often means that there is an error in ASP.NET application. More details about error could be logged to EventLog, database or plain text files. To see how to get error details take a look at Application Level Error Handling In ASP.NET tutorial.

501 Not Implemented

This is rare error. It means that web server doesn't support Http method used in request. Common Http methods are POST, GET, HEAD, TRACE etc. If some other method is used and web server can't recognize it, this error will be returned.

502 Bad Gateway

This error occurs when server is working as gateway and need to proceed request to upstream web server. If upstream web server response is not correct, then first server will return this error. The reason for this error is often bad Internet connection some problem with firewall, or problem in communication between servers.

503 Service unavailable

This error means that server is temporally down, but that is planned, usually because a maintenance. Of course, it is not completely down because it can send 503 error :), but it is not working properly. Client should expect that system administrator is working on the server and server should be up again after problem is solved.

504 Gateway Timeout

Similar to error 502 Bad Gateway, there is problem somewhere between server and upstream web server. In this case, upstream web server takes too long to respond and first server returned this error. This could happen for example if your Internet connection is slow, or it is slow or overloaded communication in your local network.

505 HTTP Version Not Supported

Web server doesn't support Http version used by web client. This should be very rare error. It could happen eventually if web client tries to access to some very old web server, which doesn't support newer Http protocol version (before v. 1.x).

Show different error pages based on roles

By using of RemoteOnly value for customErrors mode parameter in Web.config you can get detailed messages when you access through a localhost and custom messages if you access remotely. This could be a problem, because sometime you need to access remotely to web application and still see detailed messages. If you have shared hosting than this is only option. Of course, you still don't want to show error details to end users.

If you use some role based security architecture you can show detailed message to single logged user (you) or to all users that belong to some role, for example "Developers". On this way, developers logged in to web application will see detailed error messages and your users will still see just friendly custom notification.

To implement this idea we need to add some code to Application_Error procedure in Global.asax file. Code could look like this:

[ C# ]

void Application_Error(object sender, EventArgs e)
{
if(Context != null)
{
// Of course, you don't need to use both conditions bellow
// If you want, you can use only your user name or only role name
if(Context.User.IsInRole("Developers") ||
(Context.User.Identity.Name == "YourUserName") )
{
// Use Server.GetLastError to recieve current exception object
Exception CurrentException = Server.GetLastError();

// We need this line to avoid real error page
Server.ClearError();

// Clear current output
Response.Clear();

// Show error message as a title
Response.Write("<h1>Error message: " + CurrentException.Message + "</h1>");
// Show error details
Response.Write("<p>Error details:</p>");
Response.Write(CurrentException.ToString());
}
}
}

[ VB.NET ]

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
If Context IsNot Nothing Then
' Of course, you don't need to use both conditions bellow
' If you want, you can use only your user name or only role name
If Context.User.IsInRole("Developers") Or _
(Context.User.Identity.Name = "YourUserName") Then

' Use Server.GetLastError to recieve current exception object
Dim CurrentException As Exception = Server.GetLastError()

' We need this line to avoid real error page
Server.ClearError()

' Clear current output
Response.Clear()

' Show error message as a title
Response.Write("<h1>Error message: " & _
CurrentException.Message & "</h1>")
' Show error details
Response.Write("<p>Error details:</p>")
Response.Write(CurrentException.ToString())
End If
End If
End Sub

ASP.NET Custom Error Pages Remarks

By using custom error pages you can achieve more professional look for your ASP.NET web application. Although your visitors will not be happy if something is not working, it will be much better if you told them that something is wrong, but you are aware of that and you will correct it as soon as possible. That will connect you closer to your users. Errors are almost unavoidable, but your competence to deal with them makes difference.

I hope that you find this tutorial helpful. Happy programming!

Error Tracking in asp.net

Application Level Error Handling in ASP.NET

ASP.NET provides many different ways for error handling. Error handling starts on page level with try-catch blocks and Page_Error procedure. To find out more about this see Errors and Exceptions in ASP.NET tutorial. This tutorial goes one step further and explains error handling on Application level. This includes handling errors with Application_Error procedure in Global.asax or by using custom http module. These methods are usually used to log error details in text file, database or Windows EventLog, or to send notification e-mails to administrator.

Handling errors in Application_Error in Global.asax

Global.asax is optional file. Your site can work without it, but it could be very useful. You can have only one Global.asax in the root folder of your web site. Global.asax contains Application_Error procedure which executes whenever some unhandled error occurs. By using Application_Error, you can catch all unhandled errors produced by your web site, and then write a code to save error messages to database, text file or Windows EventLog, send notificationn e-mail, write some message to user, redirect user to other page with Response.Redirect etc. If you used Server.ClearError() in Page_Error procedure, Application_Error in Global.asax will not execute. Implementation code is similar to Page_Error code above:

[ C# ]

void Application_Error(object sender, EventArgs e)
{
// Get current exception
Exception CurrentException = Server.GetLastError();
string ErrorDetails = CurrentException.ToString();433333

// Now do something useful, like write error log
// or redirect a user to other page
...
}

or

protected void Application_Error(Object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;

Exception ex = ctx.Server.GetLastError().InnerException;
string errorInfo = "\r\n\r\nTime: " + DateTime.Now.ToString() +
"\r\nOffending URL: " + ctx.Request.Url.ToString() +
"\r\nIP:" + ctx.Request.ServerVariables["remote_addr"] +
"\r\nSource: " + ex.Source +
"\r\nMessage: " + ex.Message +
"\r\nRefer: " + ctx.Request.ServerVariables["http_referer"] +
"\r\nUser Agent: " + ctx.Request.ServerVariables["http_user_agent"] +
"\r\nStack trace:\r\n " + ex.StackTrace;

System.IO.StreamWriter sw = new System.IO.StreamWriter(Application["strErrorLog"].ToString(), true);
sw.Write(errorInfo);
sw.Close();

ctx.Server.ClearError();
}

[ VB.NET ]

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Get current exception
Dim CurrentException As Exception = Server.GetLastError()
Dim ErrorDetails As String = CurrentException.ToString()

' Now do something useful, like write error log
' or redirect a user to other page
...

End Sub

Writing errors to EventLog

One of the ways to track errors is to write them to EventLog. If your web site is on shared hosting you probably can't write to EventLog because of security issues. If you are on dedicated server, you need to enable "Full control" to EventLog for ASPNET account. You can do this in Registry Editor. Go to Start menu -> Run... and type regedt32 or regedit and press Enter. Registry Editor will show. Go to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog\, right mouse click and select Permissions... from context menu, like in image bellow.

Registry editor
Registry editor

Click on Permissions... item to show a dialog. Give Full Control to your ASP.NET Machine Account, like in next image (include child objects too!).

Registry permissions dialog
Registry permissions dialog

Now ASPNET account has enough rights. To write in EventLog we can use Try...Catch syntax or Page_Error event, but to avoid duplication of code better option is to use Application_Error in Global.asax file. Code inside Application_Event procedure will be executed every time when some error occurs on web site.

[ C# ]

void Application_Error(object sender, EventArgs e)
{
// Get current exception
Exception CurrentException = Server.GetLastError();

// Name of the log
string SiteLogName = "My Web Site Errors";

// Check if this log name already exists
if (EventLog.SourceExists(SiteLogName) == false)
{
EventLog.CreateEventSource(SiteLogName, SiteLogName);
}

// Write new error log
EventLog NewLog = new EventLog();
NewLog.Source = SiteLogName;
NewLog.WriteEntry(CurrentException.ToString(), EventLogEntryType.Error);
}

[ VB.NET ]

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Get current exception
Dim CurrentException As Exception = Server.GetLastError()

' Name of the log
Dim SiteLogName As String = "My Web Site Errors"

' Check if this log name already exists
If EventLog.SourceExists(SiteLogName) = False Then
EventLog.CreateEventSource(SiteLogName, SiteLogName)
End If

' Write new error log
Dim NewLog As EventLog = New EventLog()
NewLog.Source = SiteLogName
NewLog.WriteEntry(CurrentException.ToString(), _
EventLogEntryType.Error)
End Sub

Reading web site error messages from EventLog

After we created procedure for writing site error messages to Windows EventLog, we need to read them too. You can read these messages by using Windows Event Viewer, located in Control Panel. Also, you can show these messages on web page in some kind of report. To read EventLog error messages with ASP.NET and show them on page you can use code like this:

[ C# ]

using System;

// We need these namespace to read EventLog
using System.Diagnostics;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Load errors to EventLog object
EventLog MySiteErrorLogs = new EventLog("My Web Site Errors");

foreach(EventLogEntry SiteErrorLog in MySiteErrorLogs.Entries)
{
// Find when error occured
Response.Write("Time generated: " +
SiteErrorLog.TimeGenerated.ToString() + "<br />");
// Show error details
Response.Write(SiteErrorLog.Message + "<hr />");
}
}
}

[ VB.NET ]

Imports System

' We need these namespace to read EventLog
Imports System.Diagnostics

Partial Class DefaultVB
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Load errors to EventLog object
Dim MySiteErrorLogs As EventLog = New EventLog("My Web Site Errors")

For Each SiteErrorLog In MySiteErrorLogs.Entries
' Find when error occured
Response.Write("Time generated: " & _
SiteErrorLog.TimeGenerated.ToString() & "<br />")
' Show error details
Response.Write(SiteErrorLog.Message + "<hr />")
Next
End Sub
End Class

Logging of unhandled errors to text file or database

On the same way, we can use Application_Error in Global.asax to write error message to text file or in some table in database. In this example, Application_Error procedure contains a code that writes error information to .txt file.

[ C# ]

void Application_Error(object sender, EventArgs e)
{
// Get current exception
Exception CurrentException;
CurrentException = Server.GetLastError();

// Write error to text file
try
{
string LogFilePath = Server.MapPath("ErrorLog.txt");
StreamWriter sw = new StreamWriter(LogFilePath);
// Write error to text file
sw.WriteLine(CurrentException.ToString());
sw.Close();
}
catch (Exception ex)
{
// There could be a problem when writing to text file
}
}

[ VB.NET ]

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

' Get current exception
Dim CurrentException As Exception
CurrentException = Server.GetLastError()

' Write error to text file
Try

Dim LogFilePath As String = Server.MapPath("ErrorLog.txt")

Dim sw As System.IO.StreamWriter = _
New System.IO.StreamWriter(LogFilePath)
' Write error to text file
sw.WriteLine(CurrentException.ToString())
sw.Close()
Catch ex As Exception
' There could be a problem when writing to text file
End Try
End Sub

Better error logging with Log4Net

If you simply write error details to text file you will get simple, but not scalable solution. In case of large number of concurrent users, text file could be locked for writing and you will get another error. Log4Net is more scalable solution for this problem. To find out how to use Log4Net see Using NHibernate and Log4Net in ASP.NET 2.0 applications tutorial.

How to send e-mail with error details



You can place a procedure for sending an email inside Application_Error, try-catch block or any other error handling code. Function to send email is pretty simple. In this example, code for sending notification e-mails is located in Application_Error procedure in Global.asax file. On this way e-mail will be sent whenever some undhandled error occurs.

[ C# ]

<%@ Application Language="C#" %>

<%
-- We need these namespaces to send e-mail --%>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>

<script runat="server">

void Application_Error(object sender, EventArgs e)
{
// Get current exception
Exception CurrentException = Server.GetLastError();
string ErrorDetails = CurrentException.ToString();

// Send notification e-mail
MailMessage Email =
new MailMessage("admin@yoursite.com",
"admin@yoursite.com");
Email.IsBodyHtml = false;
Email.Subject = "WEB SITE ERROR";
Email.Body = ErrorDetails;
Email.Priority = MailPriority.High;
SmtpClient sc = new SmtpClient("localhost");
sc.Credentials =
new NetworkCredential("EMailAccount", "Password");
sc.Send(Email);
}

</script>

[ VB.NET ]

<%@ Application Language="VB" %>

<%-- We need these namespaces to send e-mail --%>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>

<script runat="server">

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Get current exception
Dim CurrentException As Exception = Server.GetLastError()
Dim ErrorDetails As String = CurrentException.ToString()

' Send notification e-mail
Dim Email As MailMessage = _
New MailMessage("admin@yoursite.com", _
"admin@yoursite.com")
Email.IsBodyHtml = False
Email.Subject = "WEB SITE ERROR"
Email.Body = ErrorDetails
Email.Priority = MailPriority.High
Dim sc As SmtpClient = New SmtpClient("localhost")
sc.Credentials = _
New NetworkCredential("EMailAccount", "Password")
sc.Send(Email)
End Sub

</script>

Handling errors with custom HttpModule

Custom Http module advantage is that module doesn't require changes in your web application code. Http module will catch the same event like Application_Error procedure. To create custom Http Module, start new project in Visual Studio. Project type should be Class Library. Add code like this:

[ C# ]

using System;
using System.Web;

namespace CommonModules
{
public class ErrorHandlingModule : IHttpModule
{

public void Init(HttpApplication app)
{
app.Error += new EventHandler(this.HandleErrors);
}

public void HandleErrors(object o, EventArgs e)
{
// Get current exception
Exception CurrentException = ((HttpApplication)o).Server.GetLastError();

// Now do something with exception with code like in examples before,
// send e-mail to administrator,
// write to windows EventLog, database or text file
}

public void Dispose()
{
// We must have this procedure to implement IHttpModule interface
}
}
}

[ VB.NET ]

Imports System
Imports System.Web

Namespace CommonModules
Public Class ErrorHandlingModule
Implements IHttpModule

Public Sub Init(ByVal app As HttpApplication)
app.Error += New EventHandler(this.HandleErrors)
End Sub

Public Sub HandleErrors(ByVal o As Object, ByVal e As EventArgs)
' Get current exception
Dim CurrentException As Exception = (CType(o, _
HttpApplication)).Server.GetLastError()

' Now do something with exception with code like in examples before,
' send e-mail to administrator,
' write to windows EventLog, database or text file
End Sub

Public Sub Dispose()
' We must have this procedure to implement IHttpModule interface
End Sub
End Class
End Namespace

To use the module in web application, you need to add few lines in Web.Config file.

<httpModules>
<add name="ErrorHandlingModule" type="CommonModules.ErrorHandlingModule, CommonModules "/>
</httpModules>

More about how to create and implement custom Http modules in ASP.NET see in How To Create Your Own Http Module tutorial.

ASP.NET Error Handling Remarks

Be careful to handle possible errors in your Application_Error procedure. This procedure is executed when every error occurs, so Application_Error will call itself and it is possible to go in to infinite loop.

Writing error logs to text file can cause a problem with concurrency if a lot of errors need to be logged simultaneously. To make this task easier, you can use Log4Net. Also, there is pretty nice complete solution called Elmah now available at Google code.

Popular Posts