.NET: How to convert Exception to string?

前端 未结 10 620
隐瞒了意图╮
隐瞒了意图╮ 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:55

    I first tried Jason's answer (at the top), which worked pretty well, but I also wanted:

    • To loop iteratively through inner exceptions and indent them.
    • Ignore null properties and increases readability of the output.
    • It includes the metadata in the Data property. (if any) but excludes the Data property itself. (its useless).

    I now use this:

        public static void WriteExceptionDetails(Exception exception, StringBuilder builderToFill, int level)
        {
            var indent = new string(' ', level);
    
            if (level > 0)
            {
                builderToFill.AppendLine(indent + "=== INNER EXCEPTION ===");                
            }
    
            Action append = (prop) =>
                {
                    var propInfo = exception.GetType().GetProperty(prop);
                    var val = propInfo.GetValue(exception);
    
                    if (val != null)
                    {
                        builderToFill.AppendFormat("{0}{1}: {2}{3}", indent, prop, val.ToString(), Environment.NewLine);
                    }
                };
    
            append("Message");
            append("HResult");
            append("HelpLink");
            append("Source");
            append("StackTrace");
            append("TargetSite");
    
            foreach (DictionaryEntry de in exception.Data)
            {
                builderToFill.AppendFormat("{0} {1} = {2}{3}", indent, de.Key, de.Value, Environment.NewLine);
            }
    
            if (exception.InnerException != null)
            {
                WriteExceptionDetails(exception.InnerException, builderToFill, ++level);
            }
        }
    

    Call like this:

            var builder = new StringBuilder();
            WriteExceptionDetails(exception, builder, 0);
            return builder.ToString();
    

提交回复
热议问题