Monday, January 14, 2008

Error handling/ error gathering code

Imports System.Data

Imports System.Data.SqlClientImports dataConnection


Partial Class ErrInfo Inherits System.Web.UI.Page

Public error_ID As String

Public errpath As String

Dim DatabaseObject As New dataConnection

Dim datareader As SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strSql As String Dim ex As Exception = dataConnection.LastError Dim ErrMsg, pageUrl, stack_info As String ErrMsg = dataConnection.LastError.InnerException.Message.ToString() pageUrl = dataConnection.lastURL.ToString stack_info = dataConnection.LastError.ToString ErrMsg = ErrMsg.Replace("'", "") ErrMsg = ErrMsg.Replace(".", "")
Dim errLine As String 'errLine = Mid(ex.ToString(), InStr(ex.ToString(), ":line") - 20, InStr(ex.ToString(), "at System") - InStr(ex.ToString(), ":line") + 20) errLine = Mid(ex.ToString(), ex.ToString().LastIndexOf(":line") + 6, 8) 'ex.ToString().LastIndexOf("at System") - ex.ToString().LastIndexOf(":line") + 20)
Dim pageArr As String() = pageUrl.Split(New [Char]() {"/"c})
Dim currDateTime As DateTime = DateTime.Now Dim errorDate As String
DatabaseObject.openDB() errorDate = currDateTime.ToString("dd/MMM/yy")
strSql = "INSERT INTO ERRORLOG VALUES ('" & dataConnection.lastURL & "','" & Request("aspxerrorpath").ToString & "','" & ErrMsg & "','" & errorDate & "')"
DatabaseObject.executeNonQuery(strSql) datareader = DatabaseObject.executeReader("SELECT IDENT_CURRENT('ERRORLOG') as error_id") If datareader.HasRows Then datareader.Read() error_ID = datareader("error_id").ToString End If
datareader.Close() datareader.Dispose()
DatabaseObject.closedb()
'send error mail to admin Dim body As String body = "

<table cellspacing="'3'" cellpadding="'3'" width="'90%'" align="'center'" border="'0'">" body += " Error Date: " & errorDate & "" body += " Error Time: " & Date.Now.ToString("HH:mm:ss tt") & "" body += " User Name: " & Session("userID") & "" body += " OS: " & Request.Browser.Platform & "" body += " Browser: " & Request.Browser.Browser & "" body += " Page: " & Request("aspxerrorpath").ToString & "" body += " URL: " & dataConnection.lastURL & "" body += " Line: " & errLine & "" body += " Error Details: " & ErrMsg & " " body += " Stack Information: " & stack_info & " " body += "</table>

"
Dim page_name As String = Request("aspxerrorpath").Substring(1) 'Response.Write(body & "
" & page_name) DatabaseObject.sendMail1(body, "admin@yoursite.com", "cc", "Error on file " & page_name) 'DatabaseObject.sendMail1(body, "admin@yoursite.com", "cc", "Error on ..") End Sub

End Class

add following in global.asax:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) ' Code that runs when an unhandled error occurs dataConnection.LastError = Server.GetLastError() dataConnection.lastURL = Request.Url().ToString End Sub

add following in web.config:

<customErrors mode="Off" defaultRedirect="ErrInfo.aspx">

No comments: