Follow us

Wednesday, March 16, 2011

C# code for handling Global Exceptions in ASP.NET


After you take your web application live, you are no longer the only one who is using it (hopefully), so you need an effective plan to track exceptions when they occur while others are surfing your site.
A great way to do this is to implement an exception handler at the application level. This will allow you to consolidate the logging and notification parts of your exception handling in one convenient place.
Global exception handler can handle both specific exceptions that you trap in your code and generic unhandled exceptions. After your global exception handler has done its work, you'll want to redirect the users of your website to a friendly page that tells them that something has gone wrong, and then provide them with customer support information as well as a link back to your web application's home page.

How can we implement Global Exceprtion Handler in ASP.NET

Add a Global Application Class (Global.asax) to your website/application.

Add a Code for handling global Exception Handling

You have to add following code to the Global.asax file and also you have  to be sure to set a reference to the System.Diagnostics namespace.

On getting any exception, user will be redirected to error.aspx with possible exception as its query string.

void Application_Error(object sender, EventArgs e)
        // Code that runs when an unhandled error occurs

        //get reference to the source of the exception chain
        Exception ex = Server.GetLastError().GetBaseException();

        string message = "MESSAGE: " + ex.Message + "\nSOURCE: " + ex.Source + "\nFORM: " + Request.Form.ToString() + "\nQUERYSTRING: " + Request.QueryString.ToString() + "\nTARGETSITE: " + ex.TargetSite + "\nSTACKTRACE: " + ex.StackTrace;
        System.Diagnostics.EventLog.WriteEntry("Technoscatter - Drive to Technology", message, System.Diagnostics.EventLogEntryType.Error);

        Response.Redirect("error.aspx?err=" + ex.Message);

Add a User Friendly Page

Next step is to add a aspx or HTML template on which user will be redirected on encountering an exception.

How to keep track of exceptions.

You can have a look over all the exceptions by accessing Event Viewer
Image below will demonstrate how logged exception will look like in Event Viewer. Shortcut for accessing Event Viewer is as follows:
Go to RUN and type eventvwr.msc.

Download the sample code

Sr.No Download Size
1 Global Exception Handling 4.91 KB

Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

0 comments: on "C# code for handling Global Exceptions in ASP.NET"

Post a Comment