.NET: How to convert Exception to string?

前端 未结 10 621
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 10:47

When an exception is thrown (while debugging in the IDE), i have the opportunity to view details of the exception:

10条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-30 10:51

    ErrorCode is specific to ExternalException, not Exception and LineNumber and Number are specific to SqlException, not Exception. Therefore, the only way to get these properties from a general extension method on Exception is to use reflection to iterate over all of the public properties.

    So you'll have to say something like:

    public static string GetExceptionDetails(this Exception exception) {
        var properties = exception.GetType()
                                .GetProperties();
        var fields = properties
                         .Select(property => new { 
                             Name = property.Name,
                             Value = property.GetValue(exception, null)
                         })
                         .Select(x => String.Format(
                             "{0} = {1}",
                             x.Name,
                             x.Value != null ? x.Value.ToString() : String.Empty
                         ));
        return String.Join("\n", fields);
    }
    

    (Not tested for compliation issues.)

    .NET 2.0 compatible answer:

    public static string GetExceptionDetails(this Exception exception) 
    {
        PropertyInfo[] properties = exception.GetType()
                                .GetProperties();
        List fields = new List();
        foreach(PropertyInfo property in properties) {
            object value = property.GetValue(exception, null);
            fields.Add(String.Format(
                             "{0} = {1}",
                             property.Name,
                             value != null ? value.ToString() : String.Empty
            ));    
        }         
        return String.Join("\n", fields.ToArray());
    }
    

提交回复
热议问题