【问题标题】:C# Exceptions to Dictionary [closed]字典的 C# 异常[关闭]
【发布时间】:2015-01-06 20:25:53
【问题描述】:

是否有任何方法(或库可能)可以将 C# 异常(包括 SQL 和实体框架)转换为包含任何特定数据到异常以及 InnerException 的字典?

【问题讨论】:

  • 异常类有数据属性字典?不清楚你想要什么。

标签: c# exception logging exception-handling


【解决方案1】:

我认为这是您需要自己编写的内容。试试这样的:

public IDictionary<string, object> ToDictionary(Exception ex)
{
    var returnValue = new Dictionary<string, object>();

    returnValue.Add("Message", ex.Message);
    returnValue.Add("...", ex....);

    return returnValue;
}

但是这里没有内置函数...

【讨论】:

    【解决方案2】:

    这就是我想要的。但是将异常序列化为 json 会更好。

    public static Dictionary<string, object> ToDictionary(this Exception ex)
        {
            var exceptionData = ex.GetType()
                   .GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.Name != "InnerException")
                   .ToDictionary(prop => prop.Name, prop => prop.GetValue(ex, null));
    
            exceptionData.Add("Type", ex.GetType().ToString());
    
            if (ex.InnerException != null)
            {
                var innerExceptionData = ex.InnerException.ToDictionary();
                if ((exceptionData != null) && (innerExceptionData != null))
                {
                    foreach (var keyPair in innerExceptionData)
                    {
                        exceptionData.Add(string.Format("InnerException.{0}", keyPair.Key), keyPair.Value);
                    }
                } 
    
            }
    
            return exceptionData;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多