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

3 Comments

  • The other thing you can do is download the Microsoft Exception Management Application Block and then you can just call:



    ExceptionManager.Publish(exp)



    By default it will write it to the EventLog but you can write you own plug-ins to do whatever (eg send emails, generate log files, write to the database). And it can all be configured in a simple configuration file.

  • I've heard that the EMAB is not very user friendly yet. In fact, I had a coleague try to write a plug-in for it, and he had a hard time cause it was so abstract. <shrugs> Maybe we need to revisit it again.

  • The time has come

    The hour is now

    Don't write to event logs

    Come massage my cow



    incidently the EMAB is great and with 2 hrs work i was able to knock up 6 different scenarios that implement it out of the box.

    Rock on young dudes!

Comments have been disabled for this content.