Thursday, January 10, 2008

Catch Your Application Errors

You must be thinking that your web site is working great and generating no errors. But have you ever tried catching errors on Application_Error event in Global.asax, it catches all unhandled errors. Try applying the following code, and you will be amazed to see that your site is generating some errors which you were not even aware of. The following method will dump all the erros into a XML file which will be create on monthly basis. Initially I was sending these errors to my email, but it is not easy to analyze all the data at once. XML file can be imported in Excel easily and you can fix the code which is generating more errors.

Drop the following lines of code in your global.asax file - Make sure you choose one format, otherwise you will logging errors twice.

 Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

        Dim exc As Exception = Web.HttpContext.Current.Server.GetLastError()

        If TypeOf exc Is Web.HttpUnhandledException Or exc.InnerException IsNot Nothing Then exc = exc.InnerException

 

        If exc IsNot Nothing Then

            'Attribute Format - Small File Size - less readability

            Call LogErrorAsXMLFileAttribute(exc, Request.ServerVariables("SERVER_NAME"), Request.ServerVariables("REMOTE_ADDR"), Request.ServerVariables("HTTP_REFERER"))

 

            'Element Format  - Large File Size - more readability

            'Call LogErrorAsXMLFileElement(exc, Request.ServerVariables("SERVER_NAME"), Request.ServerVariables("REMOTE_ADDR"), Request.ServerVariables("HTTP_REFERER"))

        End If 

End Sub

 

The Subroutines LogErrorAsXMLFileAttribute and LogErrorAsXMLFileElement are available on my previous post.

No comments: