Error Handling Correction
Today I realized a huge problem with the global.asax error handling method that I provided in my last entry. The problem is that if you ever run into compilation errors you are left completely in the dark as to what page it came from. You just have the date, logged in user and ip address which isn’t very helpful.
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.IO" %>
<script runat="server">
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim err As Exception = Server.GetLastError()
Dim ctx As HttpContext = HttpContext.Current
' Collect useful data
Dim user As String = ctx.Request.ServerVariables("AUTH_USER")
Dim ip As String = ctx.Request.ServerVariables("REMOTE_ADDR")
Dim filename As String = ctx.Request.PhysicalApplicationPath & "errors.txt"
Dim sw As StreamWriter = File.AppendText(filename)
sw.WriteLine("--------------------------------- ")
sw.WriteLine("ERROR: [ " & Date.Now() & " ] [ " & user & " ] [ " & ip & " ]")
sw.WriteLine("URL: " & ctx.Request.Url.AbsolutePath)
sw.WriteLine("QUERYSTRING: " & ctx.Request.QueryString.ToString)
sw.WriteLine("FORM: " & ctx.Request.Form.ToString)
sw.WriteLine("REFERER: " & ctx.Request.ServerVariables("HTTP_REFERER"))
Dim cnt As Integer = 0 ' Avoid infinite looping (just in case)
err = err.InnerException
While cnt < 5 And Not err Is Nothing
If cnt = 0 Then
sw.WriteLine("======== EXCEPTION ========")
Else
sw.WriteLine("----- INNER EXCEPTION -----")
End If
sw.WriteLine("MESSAGE: " & err.Message)
sw.WriteLine("TYPE: " & err.GetType().ToString)
sw.WriteLine("SOURCE: " & err.Source)
sw.WriteLine("TARGETSITE: " & err.TargetSite.ToString)
sw.WriteLine("STACKTRACE:" & vbNewLine & err.StackTrace)
err = err.InnerException
cnt += 1
End While
' Finalize writing to file
sw.WriteLine(vbNewLine)
sw.Close()
End Sub
</script>
Now you will get the header and the page the error occurred on in all circumstances. Additionally there is less duplication since the form string is extremely long due to the viewstate and would be repeated in the event of an inner exception.