MVC4:如何将自定义错误日志+异常传递给Elmah?

时间:2013-07-15 13:00:59

标签: asp.net asp.net-mvc asp.net-mvc-4 elmah

我想将一些自定义错误消息以及引发的异常传递给elmah源代码。例如我有课

public class Activity
{
   public string Id { get; set; }      
   public Committee Committee { get; set; }       
    public Contact Contact { get; set; }
    [Range(1950, 2050, ErrorMessage = "{0} must be between {1} and {2}.")]
    [DisplayName("Activity End Date")]
    public int? EndDate { get; set; }       
    [DisplayName("Source")]
    public string Source { get; set; }
    [DisplayName("Activity Role")]
    public string Role { get; set; }
    [DisplayName("Comments")]
    public string Comments { get; set; }
}

当引发异常时,我的异常中没有这个类prop值。所以我想把这些值和异常传递给elmah。

现在我在做

 catch (Exception exception)
            {

                Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
                return View("Error");
            }

我该怎么办?

1 个答案:

答案 0 :(得分:3)

覆盖您班级中的ToString()方法并提升异常:

catch (Exception exception)
{
  var newException = new Exception(yourClass.ToString(), exception);
  Elmah.ErrorSignal.FromCurrentContext().Raise(newException);
}

Activity课程中:

public override string ToString()
{
   //return concatenate the property names and values here .... 
}