3

I have a custom exception, where I have overriden the Data property using reflection like the following...

public class MyCustomException : Exception
{
    private readonly SomeModel _log;
    public MyCustomException(SomeModel log)
        : base(string.Format("Could not insert to some table"))
    {
        _log = log;
    }

    public override System.Collections.IDictionary Data
    {
        get
        {
            var data = new Dictionary<string, object>();
            foreach (PropertyInfo pinfo in _log.GetType().GetProperties())
            {
                data.Add(pinfo.Name, pinfo.GetType().GetProperty(pinfo.Name));
            }
            return data;
        }
    }
}

When the above exception is thrown, it gets logged to elmah but the Data is not logged.

What changes do I have to make so that the Data is also logged to elmah ? Please advice.

4

3 回答 3

1

对象的Detail属性Elmah.Error——然后由一个ErrorLog类处理——是从ToString()异常的方法构建的。

// Elmah.Error
public Error(Exception e, HttpContext context)
{
    // snip
    this._detail = e.ToString(); // here
    // snip

将您的数据添加到 ToString 方法的覆盖中MyCustomException以在 Elmah 中查看它。

于 2014-10-02T08:21:42.570 回答
1

您的问题目前是 ELMAH 问题跟踪器上大多数明星的问题:

https://code.google.com/p/elmah/issues/detail?id=162

于 2014-10-08T05:17:56.577 回答
1

@samy 可能更正确,但我也找到了另一种适合我情况的可能选项。我在一个 webapi2 项目中使用 elmah,其中用户是匿名的,在一个特定的控制器中,我想记录来自 viewmodel 的请求的一些上下文(在我的情况下,是一个电子邮件地址,但我可能会记录更多数据),我想成为能够将错误与电子邮件相关联,以便在出现错误后确定同一用户是否能够成功提交订单。

在我的控制器中,我在一个事务中执行多个数据库调用,然后向贝宝提交订单,所有这些都在一个 try/catch 块中。在 catch 中,我使用包含电子邮件的消息创建一个新的异常实例,并将 innerException 属性设置为抛出的异常并抛出新的异常。

我知道可能会丢失一些堆栈跟踪信息,我在我的上下文中对此进行了测试,堆栈跟踪似乎得到了维护,但是控制器内部发生了异常,因为这个特定的控制器和应用程序没有很多层。如果有人有类似的情况,这种方法可能是最快和最简单的。

catch (Exception ex)
{
    Exception newException = new Exception(viewModel.ContactEmail, ex);
    throw newException;
}

这假设您有一个异常过滤器,如下所示(用于 webapi),并且该过滤器在 global.asax 中注册为全局。

public class LogExceptionAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        if (HttpContext.Current != null)
        {
            ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);
        }
    }
}
于 2016-06-08T17:03:16.473 回答