【问题标题】:Sending E-Mail With Error Details from ASP.Net (VB.Net)从 ASP.Net (VB.Net) 发送带有错误详细信息的电子邮件
【发布时间】:2014-07-12 01:21:34
【问题描述】:

我猜这个问题的答案要么非常简单,要么完全没有,但我想我还是会试一试......

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

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 相关,因为“处理”错误也会停止事件日志的写入。

【问题讨论】:

  • 它应该可以正常工作。您提供的内容没有任何问题。也许问题出在 SendError 上。

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    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
    

    附: 很少有像ELMAH 这样的模块可以用来记录xml、数据库中的错误或通过电子邮件发送。

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2018-07-06
      相关资源
      最近更新 更多