Monday, October 27, 2008

Error Handling techniques in ASP.NET 2.0

Error Handling techniques in ASP.NET 2.0
How to debug and handle error in your ASP.NET applications

Introduction

In this article, I would like to explain about Error Handling in ASP.NET. How to handle the error in ASP.NET 2.0 when an error happens in your website, how to handle unhandled error, tips and tricks for better error handling and also I would give some sample code on how to do Error notifications to you as website owner if there is an error happen in your site.
Main
Error always happen on all applications regardless of whether it is web, console or windows applications. In this article, we will explain about Error handling in ASP.NET application.

In .NET framework , the simplest and easiest way to handle your code error is by placing your code inside try and catch blocks. However this doesn't mean that after you put all your code inside the try and catch blocks, you can say that you have handle all error in your site completely. There are some situation where unhandled exception error on your site. When this happens, normally user will be redirected to default ASP.NET error page or they will see the default IIS error pages. ASP.NET Framework provides you with a Library called Server.GetLastError(). This code can be used to trapped all the unhandled error in your web applications.

In ASP.NET there are three places you can set for handling these unhandled error.

1. Web.config files
2. In the global.asax file's Application_Error
3. On the aspx or associated codebehind page in the Page_Error.

The actual order of error handling events is as follows:

1. On the Page itself, in the Page_Error event handler
2. The global.asax Application_Error event handler
3. The web.config file

Note: To cancel the bubbling up of the error at anytime for the Page_Error or Application_Error, call the "Server.ClearError" function in your sub.
Each method has its own uses, as I will explain

Using the Page_Error Event Handler
The first line of unhandled error will go through your Page_Error handler event. Every unhandled error occured on your page will be trapped inside the Page_Error Event handler. To handle error in this event handler is quite simple. You can use built in ASP.NET Server Objects to get the LastError and then it is up to you how to handle the code. You can send an email, or log into database.

Code Sample in C#

//Get the Error.
System.Exception anError = Server.GetLastError();
//Now Send Email to the owner
System.Web.Mail.MailMessage oMessage = new System.Web.Mail.MailMessage();
oMessage.Subject = "Error happened in my Website";
oMessage.To = "owner@owner.com";
oMessage.Body = "Error Message is " + anError.Message + "\n\rError Stack
Trace is " + anError.StackTrace;
System.Web.Mail.SmtpMail.SmtpServer = "localhost";
System.Web.Mail.SmtpMail.Send(oMessage);
Server.ClearError();

Code Sample in VB.NET

Protected Overrides Sub OnError(ByVal e as System.EventArgs) {
Dim anError As System.Exception = Server.GetLastError();
Dim oMessage As New System.Web.Mail.MailMessage()
oMessage.Subject = "Error happened in my Website";
oMessage.To = "owner@owner.com";
oMessage.Body = "Error Message is " & anError.Message & "\n\rError Stack
Trace is " & anError.StackTrace;
System.Web.Mail.SmtpMail.SmtpServer = "localhost"
System.Web.Mail.SmtpMail.Send(oMessage)
Server.ClearError()
}

Notice on the line we called Server.ClearError(). This is very important if you do not want the error handler being routed or handled on the Global.asax errror handler or web.config error handler.

The Page_Error event handler only covers the error that occured on your page only and not on the page that do not have the Page_Error event handler. If you want to trap the error on the whole website with just single place of code, then you might consider using Global.asax or web.config files as discussed below.
Using the Global_asax Error Handler

The global.asax Error handler can be used to handle error that occurs in your whole web applications and in fact this is the easiest way to place your code handling error code. I used to putmy code handling code inside the global.asax.

After the Page_Error is called, the Application_Error handler is called. Here you can also log the error and redirect to another page. I won't explain anything else about it because it is basically the same as the Page_Error but happens to be at the application level rather than the page level.

Using the Web.config files Error Handler
The customErrors element of the web.config file is the last line of Error handler being called by .NET Engine against an unhandled error. If you have other error handlers in place, like the Application_Error of Page_Error subs, these will get called first.

Provided they don't do a Response.Redirect or a Server.ClearError, you should be brought to the page(s) defined in the web.config.

In the web.config file, you can handle specific error codes (500, 404, etc), or you can use one page to handle all errors. This is a major difference between this method and the others (although you can emulate this by doing various Response.Redirects using the other methods). Open up your web.config file. The customErrors section uses this format:





Here is some important information about the "mode" attribute:
"On" specifies that custom errors are enabled. If no defaultRedirect is specified, users see a generic error.

"Off" specifies that custom errors are disabled. This allows display of detailed errors.

"RemoteOnly" specifies that custom errors are shown only to remote clients, and ASP.NET errors are shown to the local host. This is the default. By default, the section looks like this when you create a Web application.




This will show a generic page to users. To redirect it to one of your own pages, you would change it to this:




To handle specific errors, and redirect to the error page for everything else you can specify the error code you want specially handled like so:








There is a problem here with this solution. Once the redirect is done, your error information is no longer available on the redirected page. Therefore if you try to do Server.GetLastError() in your error.aspx, you will get an Exception.

This is because .net framework performs a plain old GET request to the error page and does not do a "Server.Transfer" like the built-in IIS error handling does.
The only information available to you at this time is the URL that caused this error to be raised. This is located on the querystring as "aspxerrorpath": http://URL/ErrorHandling/error.aspx?aspxerrorpath=/ErrorHandling/WebForm1.aspx.

Conclusion

By doing a proper error handling on your website, you can avoid any unprofessional .NET Error to your user and in the other hand, you know what is happening to your website so you can prevent the error from happening again. In the code sample above,you can see that we are using Email notifications when the error happens. For better error logging, you can actually store all the details in your database,so that you can have the history and easier for you to manage code error on your site.

No comments: