
Introduction
This text was based on the article "Global Exception Handling with ASP.NET" found at webdeveloper.earthweb.com
So, you've just finished your Web Application using ASP.NET. Everythings seems to be working fine. But how to be notified if an error happens while the site is running? A solution to this problem is shown in this article.
Handling Errors in a ASP.NET application
First of all you must catch the unhandled exceptions that happen in your Web Application by handling the HttpApplication
Error
event. You accomplish this task by editing your Global.asax file as follow:
protected void Application_Error(object sender, EventArgs e)
{
Exception excpt = Server.GetLastError().GetBaseException();
}
How to be notified about those unhandled exceptions?
The 3 most common ways to be notified about those "programming mistakes" are: File Log, EventLog and Email. As you would imagine I wrote a simple class that does this notifing stuff according to your Web.Config settings. You can see below a sample Web.Config file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!--
<appsettings>
<!--
<!--
<add key="errorNotifier_NotifyMode" value="3" />
<!--
<add key="errorNotifier_EventLogSource" value="Sample App error" />
<!--
<add key="errorNotifier_Filename" value="error.txt" />
<!--
<add key="errorNotifier_EmailTo" value="error@mydomain.com" />
<!--
<add key="errorNotifier_EmailFrom" value="errornotifier@mydomain.com" />
<!--
<add key="errorNotifier_EmailSubject" value="Error in ASP.NET app" />
<!--
<add key="errorNotifier_EmailSmtpServer" value="mySmtpServerAddress" />
</appsettings>
<system.web>
Now change the Application_Error
event implementation in your Global.asax as something as:
protected void Application_Error(object sender, EventArgs e)
{
XC.Web.ErrorHandler handler = new XC.Web.ErrorHandler();
handler.HandleException();
}
You can also make you Web Application show a special page whenever an error happens, giving a better feedback to your users. To do it, edit your Web.Config file as follow:
<system.web>
...
<customerrors mode="Off" defaultRedirect="~/myErrorPage.aspx" />
...
</system.web>
Possible values to mode
:
On
: you want to handle errors RemoteOnly
: the errors will be handled only when they happen in a box differents than the IIS's. That's useful for debugging Off
: you don't want to handle errors at all
The defaultRedirect
value is the url that should be shown in case of a unhandled exception
It's important to note that the ASP.NET user must have the right to write to the EventLog in case this method of notification is used. Also it must have write permission to the directory of the log file, if apply.
XicoLoko is a brazilian developer based in Switzerland.