记录任何类型的异常的所有异常信息

Van*_*nel 5 c# asp.net-mvc log4net entity-framework exception

我正在使用C#,ASP.NET MVC Web Api,实体框架和.NET Framework 4.0进行开发.

我有这个代码来记录异常:

public void LogCompleteException(
    string controllerName,
    string actionName,
    Exception exception)
{
    string exceptionMessage = string.Empty;

    Exception e = exception;
    if (e.InnerException == null)
        e = null;
    else
        while (e.InnerException != null) e = e.InnerException;

    if (e == null)
        exceptionMessage = exception.Message;
    else
        exceptionMessage = string.Format("{0}\n\rInnerException: {1}", exception.Message, e.Message);

    _logger.ErrorFormat(
        LogTextFormatString,
        ExceptionText,
        controllerName,
        actionName,
        exceptionMessage);
}
Run Code Online (Sandbox Code Playgroud)

但是在我的日志文件中我发现了这个:

一个或多个实体的验证失败.有关详细信息,请参阅"EntityValidationErrors"属性.

当我编写'See'EntityValidationErrors'属性以获取更多详细信息.', 我只是展示了一个我没有记录重要属性的示例.

有很多例外; 但是使用我的方法,我没有记录所有相关信息,因为可能存在我没有记录的'EntityValidationErrors'等属性.

当我传递异常来记录它时,我不知道它有什么属性,我不知道如何记录它拥有的每个属性.

你知道一种完全记录异常的方法吗?我的代码与EntityValidationErrors属性或任何其他重要属性的长期异常并不长.

我正在使用log4net进行日志记录.

Bra*_*d C 3

由于内部异常本身就是一个异常,也许您可​​以递归并重用已有的方法:

if (e.InnerException != null)
{
    LogCompleteException(controllerName, actionName, e.InnerException);
}
Run Code Online (Sandbox Code Playgroud)

但是,如果这确实有效,您仍然会丢失 EntityValidationErrors。

我最近使用的另一种方法是显式捕获并记录发生异常的位置:

try
{
    db.Add(something);
    db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
    StringBuilder sb = new StringBuilder();

    // collect some extra info about the exception before logging
    foreach (var eve in ex.EntityValidationErrors)
    {
        sb.AppendLine(String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State));
        foreach (var ve in eve.ValidationErrors)
        {
            sb.AppendLine(String.Format("Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
        }
    }

    logger.Error("There was an error while trying to parse and save something!\n" + sb.ToString(), ex);
}
Run Code Online (Sandbox Code Playgroud)

如果您想要 Exception.Data 字典条目,您也可以添加这些条目:

foreach (DictionaryEntry entry in ex.Data)
{
    // you will want to use a StringBuilder instead of concatenating strings if you do this
    exceptionMessage = exceptionMessage + string.Format("Exception.Data[{0}]: {1}", entry.Key, entry.Value);
}
Run Code Online (Sandbox Code Playgroud)

至于自定义异常类的属性,就像 EntityValidationErrors 一样,我只会捕获并解析它们发生的地方。否则,您将必须在每个异常类型上重写 ToString() 或使用一些反射黑客来枚举所有属性,这会导致日志中包含您不关心的属性。