【问题标题】:Filtering signalled exceptions out of Elmah error mails从 Elmah 错误邮件中过滤信号异常
【发布时间】:2010-08-04 14:42:14
【问题描述】:

我已经围绕 Elmah 的错误信号实现了一个包装器方法,其中只有 Elmah 可以看到引发的异常以进行日志记录和邮件发送,但现在我想仅从邮件中过滤掉这些发出信号的异常,但仍将它们记录下来.我该怎么做?

这是我的简单包装器:

    public void LogException(Exception exception)
    {
        ErrorSignal.FromContext(HttpContext.Current).Raise(exception);
    }

我曾考虑将输入异常包装在自定义 SignalledException 中,并从邮件中过滤掉这些异常,但随后我的日志中充满了 SignalledException,而不是真正的异常。

请问还有什么想法吗?

【问题讨论】:

    标签: asp.net elmah


    【解决方案1】:

    Elmah 过滤主要作用于异常类型。程序化过滤允许我检查添加到异常中的信息,但我还没有遇到具有ElmahFilteringData 属性的异常类型,而且我不想“侵入”我想要记录的异常。以下是我仅针对某些异常信号发送电子邮件通知的方法:

    首先我有一个特殊的包装异常,纯粹是为了告诉 Elmah 不要为这种类型的异常发送电子邮件通知:

    public class ElmahEMailBlockWrapperException: Exception
    {
        public const string Explanation = "This is a wrapper exception that will be blocked by Elmah email filtering.  The real exception is the InnerException";
        public ElmahEMailBlockWrapperException(Exception wrappedException):base(Explanation, wrappedException) {}
    }
    

    然后,当我提出异常时,我通常只希望记录而不是通过电子邮件发送,但有时可能会通过电子邮件发送,我在异常记录服务中使用此代码:

    public void LogException(Exception exception, bool includeEmail)
    {            
        if (includeEmail)
        {
            ErrorSignal.FromContext(HttpContext.Current).Raise(exception);
        }
        else
        {
            // Wrap the input exception in a special exception type that the Elmah email filter can block.
            var wrappedException = new ElmahEMailBlockWrapperException(exception);
            ErrorSignal.FromContext(HttpContext.Current).Raise(wrappedException);
        }
    }
    

    现在,在 Global.asax 中的 Elmah 过滤器事件中,我打开异常以记录它,如果它被包装,则从电子邮件通知管道中将其关闭:

    public void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
    {
        // If the exception was wrapped in a ElmahEMailBlockWrapperException exception to be blocked by the ErrorMail filter, the InnerException 
        // of the the ElmahEMailBlockWrapperException is the real exception to be logged, so we extract it, log it, and dismiss the wrapper.
        var ebw = e.Exception.GetBaseException() as ElmahEMailBlockWrapperException;
        if (ebw != null)
        {
            ErrorLog.GetDefault(HttpContext.Current).Log(new Error(ebw.InnerException));
            e.Dismiss();
        }
    }
    
    public void ErrorMail_Filtering(object sender, ExceptionFilterEventArgs e)
    {
        // If the exception was wrapped, i.e. raised only to be logged by Elmah and not emailed, dismiss it.
        if (e.Exception.GetBaseException() is ElmahEMailBlockWrapperException)
        {
            e.Dismiss();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-19
      • 2011-02-20
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多