ARTICLE :
 

Exception handling in ASP.NET

by RaKumar on April 7th, 2010

Introduction

Exception handling is one of the key parts of software development. Developers use various techniques to handle exception in ASP.NET application. This is one of the techniques to handle exceptions globally using global.asax page and web.config. In this article, we will discuss how we can avoid try... catch... block in every single line of code we write and handle exception globally in one single location in global.asax.

Background

As mentioned above exception / error handling is always been important in software development. We would always want to handle the exception so that we can log error, understand error and provide better experience to the end users. Traditionally, in any object oriented programming language, the known best way to handle exception is to keep the code in some kind of try... catch... block. Using try... catch... block all the time might hurt performance in some situations. We sometime hear that exception handling is expensive because sometime it may hit performance to unwind the call stack to get catch statement during exception. This article mainly consolidates the exception handling in one centralized location and handles all the exceptions for the ASP.NET application.

Detail

One easy and clean approach to handle exception in ASP.NET is to handle exception globally in global.asax page. The main benefit of the approach is that we don't have to worry about try... catch... block in any other page or code in the application. If there is an exception, it will be taken care globally by global.asax page. To enhance the end user experience, we can also define custom error page in web.config so that after error is handled by global.asax page, user will be redirected to a friendly custom error page.

Here is how it is done:

In web.config file, define custom error page:
<customErrors mode="RemoteOnly">
      <error statusCode="500" redirect="error.aspx"/>
</customErrors>

In global.asax page:
ASP.NET global.asax page provides various events and one of the event is Application_Error(). We can utilize this Application_Error() event to handle exception/errors globally. In Application_Error() event in global.asax page, add the error handling code:
protected void Application_Error(object sender, EventArgs e)
{
	//Get the exception object
	Exception exceptionObject = Server.GetLastError();
	try
	{
	    if (exceptionObject != null)
            {
                if (exceptionObject.InnerException != null)
                {
                    exceptionObject = exceptionObject.InnerException;
                }

                switch (exceptionObject.GetType().ToString())
                {
                    case "System.Threading.ThreadAbortException":
                        HttpContext.Current.Server.ClearError();
                        break;
                    default:
                        LogError() //Custom method to log error
                        break;
                }
            }
      	}
	catch { }//Avoiding further exception from exception handling
}

Here we get the last error being throw by the application using Server.GetLastError() and handle the exception. However, we need to avoid exception of type "System.Threading.ThreadAbortException" because this exception is often thrown during non exception scenarios like Response.Redirect or Response.End etc. Finally, we got the error. We can then log the exception/error either in database or in text file or however we wanted.

Conclusion

This global exception handling technique will allow centralized exception handling for entire ASP.NET application. Technically, we will not need to use try... catch... or worry about forgetting try...catch... in the code.

However, there are scenarios when we would want to use try... catch... block, understand the error and do something else based on the error. For those scenarios, we would need individual try... catch... blocks around the code so that we can do special treatment with those exceptions.

Download

Click here to download source code

Author:

Profile Photo
RaKumar
Date: April 7th, 2010

Comments:



Profile Photo
Commented by Misuk Wang
on May 26th, 2011 at 20:05:24 EST
Nice article. I will try this in our .net application as well.