Have your website e-mail you errors
A friend requested that I post about this. It's a little snippet of code that I whipped up to e-mail me when my site craps out. It has come in handy a few times, and led me to extend the concept for a future software product of sorts. This one is different than most you'll see because I have it send me the stack trace too. You can also extend it to do any inner exceptions and inner stack traces. This is helpful when toubleshooting website components.
*shrugs* Hope this helps someone.
Instructions:
Add the code below to your global.asax.vb file (or .cs file as the case may be)
Make sure you add the following lines to the top:
Imports System.Configuration.ConfigurationSettings
Imports System.Web.Mail
If you're using C#, make sure you take out the “ConfigurationSettings” part, and add it to the places where you see “AppSettings“. In C# you cannot import classes, only namespaces.
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Fires when an error occurs
Dim Mail As New MailMessage()
'Insert website e-mail address here
Mail.From = AppSettings("SiteMailAddress")
'Insert e-mail address to admin here
Mail.To = AppSettings("AdminMailAddress")
'Subject line: E.g. 'Error in webshop'
Mail.Subject = "Unhandled Exception on " & AppSettings("SiteName")
'Get page on which error occurred
Mail.Body = Request.Path
Mail.Body &= Chr(13)
'Get type of error/error message
Mail.Body &= Context.Server.GetLastError.Message
Mail.Body &= Chr(13)
'Get the stack trace for good measure
Mail.Body &= Context.Server.GetLastError.StackTrace
'Write the smtp server to relay the mail
SmtpMail.SmtpServer = AppSettings("MailServer")
SmtpMail.Send(Mail)
'Clear the error
Context.Server.ClearError()
End Sub