从ASP.Net发送带有错误详细信息的电子邮件(VB.Net)

时间:2014-05-22 20:24:23

标签: asp.net vb.net visual-studio-2010 exception

我猜这个问题的答案要么非常简单,要么只是单调出来,但是我还是认为我还是试了一下......

是否可以添加一个函数来捕获异常时发送电子邮件?例如:

Try
     'Do Something
Catch ex As Exception
     SendError(ex.Message)
     Response.Redirect("~/ErrorPage.html")
End Try

在这种情况下,SendError函数被设置为一个简单的SMTP处理程序,它将消息发送到预定义的电子邮件帐户。显然这不起作用。我问的原因是因为如果错误没有用Try ... Catch处理,那么它会被记录在事件日志中。这很好,因为我知道用户输入何时导致问题。使用Try ... Catch,我无法在不等待用户呼入的情况下获得任何错误详细信息,甚至无法知道问题。

在这里阅读http://www.codemag.com/Article/0307081,显示对global.asax文件的修改......但我想知道这是否与Try ... Catch相关,因为"处理& #34;该错误也会停止写入事件日志。

2 个答案:

答案 0 :(得分:0)

如果SendError方法中没有任何内容可以保留消息的发送,我猜想SendMessage方法是异步的,在发送邮件之前返回。当ASP .NET遇到对Repsonse.Redirect的调用时,它会过早地终止当前请求,而不是等待SendMessage完成其工作。

看看你是否可以在调用Redirect之前等待?

答案 1 :(得分:0)

Application_Error方法将捕获未处理的异常(不带try..catch)。如您所见,该示例说明了如何使用System.Diagnostics中的EventLog记录事件日志中的错误。

要记录错误并发送电子邮件,请将您的方法更改为

Sub SendError(ByVal ErrorDescription As String)

    'Create the event log record if it does not exist
    Dim EventLogName As String = "MySample"
    If (Not EventLog.SourceExists(EventLogName)) Then
        EventLog.CreateEventSource(EventLogName, EventLogName)
    End If

    'Add a record to the new event log entry
    Dim Log As New EventLog()
    Log.Source = EventLogName
    Log.WriteEntry(ErrorDescription, EventLogEntryType.Error)

    'Send an email to admin when site wide error occurs
    Dim mail As New MailMessage()
    Dim ErrorMessage = _
       "The error description is as follows : " _
       & ErrorDescription 
    mail.From = "jduffy@takenote.com"
    mail.To = "info@takenote.com"
    mail.Subject = "Error in the Site"
    mail.Priority = MailPriority.High
    mail.BodyFormat = MailFormat.Text
    mail.Body = ErrorMessage
    SmtpMail.SmtpServer = "put.your.SMTP.server.here"
    SmtpMail.Send(mail)

End Sub

P.S。 像ELMAH这样的模块很少,可用于记录xml,数据库中的错误或通过电子邮件发送。

相关问题