First,
turn on custom error reporting in the web.config
and name the file you will use as your default handler:
<!-- Web.Config
-->
<configuration>
<system.web>
<compilation
debug="true"/>
<customErrors
mode="On" defaultRedirect="MyErrorHandler.aspx"/>
</system.web>
</configuration>
At
its simplest, that's all there is to it. Apologize to the user and provide some
links back to what they were doing before the error. But what were they doing?
What is the error? You might be disappointed that variations on the following
don't work in MyErrorHandler.aspx:
<%@ Page Language="C#" %>
<script runat="server">
private void Page_Load( object src, EventArgs e ) {
Exception objError
= Server.GetLastError();
lblMessage.Text=objError.Message;
lblSource.Text=objError.Source;
Server.ClearError();
}
</script>
<html><head><title>Server
Error</title></head>
<body><form runat="server">
<p><asp:label id="lblMessage"
runat="server" /></p>
<p><asp:label id="lblSource"
runat="server" /></p>
</form></body></html>
The
error is past tense by the time you hit the handler page. How do you find it?
Keep reading.
The
simplest thing to do is to catch and store the Exception inside the Application
bag right in your global.asax (or a
global.asax.cs codebehind):
<%@ Import Namespace="System.IO"
%>
<script language="C#" runat="server">
protected void Application_Error( object src, EventArgs e ) {
Exception objError
= Server.GetLastError();
this.Application.Add("lastException",objError);
}
</script>
And
then retrieve and the display the Exception object's properties (Exception.Message, Exception.Source,
Exception.StackTrace, or Exception.TargetSite.Name)
inside MyErrorHandler.aspx (as named in
your web.config).
private void Page_Load(
object src, EventArgs e ) {
Exception objError
= Server.GetLastError();
lblMessage.Text=objError.Message;
lblSource.Text=objError.Source;
Server.ClearError();
}
...
http://www.c-sharpcenter.com/asp.net/customerrors.htm
Advanced User Note: On a busy site, use of the
Application object impedes scalability. Application objects are a late-bound
kludge to help migrate from Classic ASP to .NET. Ideally you should grab the
Exception properties into static fields in some sort of Global class which
could then be accessed by the custom error page.
http://www.eggheadcafe.com/articles/20030211.asp
Caveat: Recognize that on a high traffic
site which generates nearly simultaneous errors, since this method records the
last error in the Application and not the last error in the Session, by the
time the Custom Error page is displayed a user could conceivably get someone
else's error message. Though not a common problem on most sites, it could
potentially confuse whoever is debugging the problem.
A
solution to this would be to write the error into a log right when it is raised
and debug with the log. The article on error handling above covers writing to
the Event Log.