Sub Application_Error(ByVal sender As Object, _ ByVal e As EventArgs) ' Get the current time Dim CurrentTime As DateTime = DateTime.Now() ' Get the stored time of the last error Dim LastString As String = Application("LastErrorTime") Dim LastTime As DateTime Dim SafeTime As DateTime ' If there was a last error, figure out when it was If Len(LastString) > 0 Then LastTime = Convert.ToDateTime(LastString) ' TimeSpan(0, 1, 0) = one minute ' This calculates a time one minute before "now" SafeTime = CurrentTime.Subtract(New TimeSpan(0, 1, 0)) End If ' Only send mail if there was no last error (in ' which case the string retrieved from the application ' state will be empty) or if it's been at least one ' minute since the last mail If (Len(LastString) = 0) Or (SafeTime > LastTime) Then ' Get the actual error that brought us here Dim ex As Exception = _ Server.GetLastError.InnerException ' Create a string with the error information Dim Message As StringBuilder = New StringBuilder( _ "An error occurred in the application:" & vbCrLf) Message.Append(ex.Message & vbCrLf) Message.Append("Stack trace:" & vbCrLf) Dim s As StringBuilder = New StringBuilder(ex.StackTrace) Message.Append(s.Replace(" at ", " at " & vbCrLf)) ' Mail the message to the developer SmtpMail.Send("App@sample.com", "Dev@sample.com", _ "Application Error", Message.ToString()) End If ' Cleanup to do whether we send mail or not ' Store the time of this error Application("LastErrorTime") = Convert.ToString(CurrentTime) ' Clear the error Server.ClearError() ' Tell the user we're on top of it Response.Write("We're sorry, but an unexpected error has occurred") Response.End() End Sub |