| |
If you've ever wanted a simple way to display a custom error page in your ASP.NET application, this is the tutorial for you!
This technique is a simple, two step process. Step one is to put some error handling code in the global.asax and step two is to build your custom error page.
Step 1 - Updating the global.asax If you open up your web application's global.asax file, you'll see several functions for handling global (application level) events - much like the global.asa of old-style ASP. The function we're looking for is Application_Error. This fires whenever an error occurs in your application. Add the following code to this function:
protected void Application_Error(Object sender, EventArgs e)
{
Exception LastException = Server.GetLastError();
Response.Redirect(String.Format("~/error.aspx?msg={0}", Server.UrlEncode(LastException.Message)));
}
|
Step 2 - Create a custom error page to display when an error occurs This page can be either a static HTML page that just tells the user that something has gone wrong or an .aspx that displays a message relevant to the error that has occured. You could even add a link on this page for the user to mail support to notify them of an error! This sample page is very simple and just displays the message of the unhandled exception that was thrown - here's error.aspx:
| |
<%@ Page language="c#" Codebehind="error.aspx.cs" AutoEventWireup="false" Inherits="CustomError.error" %>
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>An Error Has Occurred</title>
<meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR">
<meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
</HEAD>
<body text="#000000" bgColor="#ffffff" leftMargin="0" topMargin="0">
<form id="frmMain" runat="server">
<p>Oh dear, something has gone wrong!</p>
<P><%= Request.QueryString["msg"]%></P>
</form>
</body>
</HTML>
|
Well, that's all folks. To test your new error page, try navigating to an .aspx that doesn't exist in your application - the 404 error will be caught by the global.asax Application_Error function and your custom page will be shown.
|
|