Handling unhandled exceptions

Όνομα: *
Το email μου: *
Email παραλήπτη: *
Μήνυμα: *
Τα πεδία με έντονους χαρακτήρες είναι υποχρεωτικά.
Δεν έχετε συμπληρώσει όλα τα απαιτούμενα στοιχεία Το email που δώσατε δεν είναι σωστό

 
We have already talked about exception handling and creating error pages on a previous article. In this article we will see how we can use the Global.asax Application_Error method to handle every possible exception in our website.
 

Introduction

 
Typical exception handling can use try catch blocks in pieces of code where an exception is likely to happen. On the other hand an error page works for all possible exceptions on our website but will do nothing more than display an error page. However it would be nice if we could be informed when an unhandled exception is thrown. Since our code is supposed to work, an unhandled exception would state that either there is something wrong with it, or someone is trying to throw exceptions on purpose, by messing up with the URL for example. 
 
Either way, we can use the Application_Error method to do things like log error info or send an email to the administrator. Application_Error will be called when an unhandled exception is thrown.
 
exception handling
 

Using the Application_Error method

 
Getting the exception info is quite easy. All we have to do is use
Exception ex = Server.GetLastError();
and here's our exception waiting for us to fetch the info we want.
 
Most important things to get are the Message, InnerException.Message and StackTrace. Using these you can get the idea of what exception has been thrown and why. For example
Message :                          Exception of type 'System.Web.HttpUnhandledException' was thrown.
InnerException.Message : Input string was not in a correct format.
StackTrace :                       at System.Web.UI.Page.HandleError(Exception e)
                                          at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)...
 
 
You can of course get all the info you like an Exception object can offer besides the ones already mentioned.
 
You may also like to write down the time the exception was thrown. This can be easily found using DateTime.Now.
 
On a web application you may probably want to get info located in the Request object. Request contains helpful attributes such as the URL that caused the exception. You may also be interested in the client's IP address.
string url = Request.RawUrl;
string IPAddress = GetIPAddress(Request);
 
 

Application_Error in action

 
The example following shows how we can use the Application_Error method to create an UnhandledException object and then store it in database.
 
First we create the UnhandledException class
public class UnhandledException
    {
        public string URL { getset; }
        public string Message { getset; }
        public DateTime DateCreated { getset; }
        public string StackTrace { getset; }
        public string IPAddress { get; set; }
 
        public UnhandledException(string url, string message, DateTime dateCreated, string stackTrace, string ipaddress)
        {
            URL = url;
            Message = message;
            DateCreated = dateCreated;
            StackTrace = stackTrace;
            IPAddress = ipaddress;
        }
 
        public int StoreUnhandledException()
        {
            //Stores UnhandledException to database.
            return StoreUnhandledException(this);
        }
    }
 
 Then we place code inside the Application_Error method
 void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs      
        string url = Request.RawUrl;
        string IPAddress = GetIPAddress(Request);
 
        // Get the exception object.
        Exception ex = Server.GetLastError();
        //Exception info
        string message = ex.Message;
        if (ex.InnerException != null)
            //InnerException.Message is more accurate than message
            message = ex.InnerException.Message;
 
        UnhandledException uex = new UnhandledException(url, message, DateTime.Now, ex.StackTrace, IPAddress);
        uex.StoreUnhandledException();
        
        //Clear exception
        Server.ClearError();
        //Redirect to error page
        Response.Redirect("~/error.aspx");      
    }
 
GetIPAddress is a method returning a string that represents the request's IP address. There are a few ways to get the IP address even though none of them is 100% accurate. In this article we may use the following  
 
//Return client's IP address
public static string GetIPAddress(HttpRequest request)
{
   //In case of proxy use etc
   string ipList = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
 
   if (!string.IsNullOrEmpty(ipList))
       //HTTP_X_FORWARDED_FOR may contain multiple addresses.
       //Get the first one.
       return ipList.Split(',')[0];
 
return request.ServerVariables["REMOTE_ADDR"];
}
 
StoreUnhandledException contains code needed to store exception info in database. Additionally you use could some other method to send an email concerning the exception etc
 
Finally, we clear the exception and redirect to an error page.
 
error handling
 

Summary

 
Storing information concerning unhandled exceptions may prove to be useful. We can use the Application_Error method located within the Global.asax file. This method will be called when an unhandled exception occurs. You can get information concerning both the exception and the request that caused it. 
 

Πίσω στο BlogΠροηγούμενοΕπόμενο

Σχόλια



    Γράψε το σχόλιό σου
    Όνομα: