Jun 30, 2008

Send .Net Runtime Error messages with Email

I have returned from vacation today. I have many works to do. I see my coworkers are not happy. Emails tell me everything. Error messages, user requests, bad test results, meetings, works, works...

In one week there are 201 .net runtime error emails. There are some problems with some developments.

We configured .net settings to emails runtime errors to us with detailed information. It is useful sometimes. But be careful, if you face many runtime errors your mailbox may be full. I recommend you to redirect error emails to your secondary email address if you have mail quota problems. If you want to use with your primary address you should filter messages and move them to new folder. So tracking error messages would be more easy.

I want to mention about how can we send error messages as we use. Our code works with .Net 1.1 version and not tested with upper versions. I think it should work with new versions.

Go to global.asax.vb and find Application_Error function. You may see "Fires when an error occurs" comment in it. In this function open try/catch block and paste code below in it.

Dim ex As Exception = Server.GetLastError().GetBaseException()
Dim ErrorMessage As String = ""
ErrorMessage = "<b>Error date :</b>" & DateTime.Now
ErrorMessage &= "<br><b>Error message : </b>" & ex.Message
ErrorMessage &= "<br><b>Error page and location :</b>" & ex.StackTrace
ErrorMessage &= "<br><b>User : </b>" & Session("ID_USER") 'If you have user info

'Submitted Form Information
ErrorMessage &= "<br><p><b><u>Form Info</u></b>"
Dim x As Integer = 0
Do While x < Request.Form.Count
ErrorMessage &= "<LI>" & Request.Form.Keys(x) & " : " & Request.Form(x) & ""
x += 1
Loop

'Server Variables
ErrorMessage &= "<p><b><u>Server Variables</u></b>"
x = 0

Do While x < Request.ServerVariables.Count
ErrorMessage &= "<LI>" & Request.ServerVariables.Keys(x) & " : " & Request.ServerVariables(x) & ""
x += 1
Loop

Dim objMsg As New System.Web.Mail.MailMessage
objMsg.BodyFormat = Mail.MailFormat.Html
objMsg.From = ConfigurationSettings.AppSettings("From")
objMsg.Subject = "Test Error! "
objMsg.To = "mail@mail.com" 'Your email address
objMsg.Body = ErrorMessage
System.Web.Mail.SmtpMail.SmtpServer = ConfigurationSettings.AppSettings("Smtp")
System.Web.Mail.SmtpMail.Send(objMsg)

Notes:
  • We keep "From" and "Smtp" variables in webconfig file. You can change it as you wish.
  • We do not email errors on production environment. Just using for test purposes.

0 comments: