.NET: How to convert Exception to string?

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

    This comprehensive answer handles writing out:

    1. The Data collection property found on all exceptions (The accepted answer does not do this).
    2. Any other custom properties added to the exception.
    3. Recursively writes out the InnerException (The accepted answer does not do this).
    4. Writes out the collection of exceptions contained within the AggregateException.

    It also writes out the properties of the exceptions in a nicer order. It's using C# 6.0 but should be very easy for you to convert to older versions if necessary.

    public static class ExceptionExtensions
    {
        public static string ToDetailedString(this Exception exception)
        {
            if (exception == null)
            {
                throw new ArgumentNullException(nameof(exception));
            }
    
            return ToDetailedString(exception, ExceptionOptions.Default);
        }
    
        public static string ToDetailedString(this Exception exception, ExceptionOptions options)
        {
            var stringBuilder = new StringBuilder();
    
            AppendValue(stringBuilder, "Type", exception.GetType().FullName, options);
    
            foreach (PropertyInfo property in exception
                .GetType()
                .GetProperties()
                .OrderByDescending(x => string.Equals(x.Name, nameof(exception.Message), StringComparison.Ordinal))
                .ThenByDescending(x => string.Equals(x.Name, nameof(exception.Source), StringComparison.Ordinal))
                .ThenBy(x => string.Equals(x.Name, nameof(exception.InnerException), StringComparison.Ordinal))
                .ThenBy(x => string.Equals(x.Name, nameof(AggregateException.InnerExceptions), StringComparison.Ordinal)))
            {
                var value = property.GetValue(exception, null);
                if (value == null && options.OmitNullProperties)
                {
                    if (options.OmitNullProperties)
                    {
                        continue;
                    }
                    else
                    {
                        value = string.Empty;
                    }
                }
    
                AppendValue(stringBuilder, property.Name, value, options);
            }
    
            return stringBuilder.ToString().TrimEnd('\r', '\n');
        }
    
        private static void AppendCollection(
            StringBuilder stringBuilder,
            string propertyName,
            IEnumerable collection,
            ExceptionOptions options)
            {
                stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
    
                var innerOptions = new ExceptionOptions(options, options.CurrentIndentLevel + 1);
    
                var i = 0;
                foreach (var item in collection)
                {
                    var innerPropertyName = $"[{i}]";
    
                    if (item is Exception)
                    {
                        var innerException = (Exception)item;
                        AppendException(
                            stringBuilder,
                            innerPropertyName,
                            innerException,
                            innerOptions);
                    }
                    else
                    {
                        AppendValue(
                            stringBuilder,
                            innerPropertyName,
                            item,
                            innerOptions);
                    }
    
                    ++i;
                }
            }
    
        private static void AppendException(
            StringBuilder stringBuilder,
            string propertyName,
            Exception exception,
            ExceptionOptions options)
        {
            var innerExceptionString = ToDetailedString(
                exception, 
                new ExceptionOptions(options, options.CurrentIndentLevel + 1));
    
            stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
            stringBuilder.AppendLine(innerExceptionString);
        }
    
        private static string IndentString(string value, ExceptionOptions options)
        {
            return value.Replace(Environment.NewLine, Environment.NewLine + options.Indent);
        }
    
        private static void AppendValue(
            StringBuilder stringBuilder,
            string propertyName,
            object value,
            ExceptionOptions options)
        {
            if (value is DictionaryEntry)
            {
                DictionaryEntry dictionaryEntry = (DictionaryEntry)value;
                stringBuilder.AppendLine($"{options.Indent}{propertyName} = {dictionaryEntry.Key} : {dictionaryEntry.Value}");
            }
            else if (value is Exception)
            {
                var innerException = (Exception)value;
                AppendException(
                    stringBuilder,
                    propertyName,
                    innerException,
                    options);
            }
            else if (value is IEnumerable && !(value is string))
            {
                var collection = (IEnumerable)value;
                if (collection.GetEnumerator().MoveNext())
                {
                    AppendCollection(
                        stringBuilder,
                        propertyName,
                        collection,
                        options);
                }
            }
            else
            {
                stringBuilder.AppendLine($"{options.Indent}{propertyName} = {value}");
            }
        }
    }
    
    public struct ExceptionOptions
    {
        public static readonly ExceptionOptions Default = new ExceptionOptions()
        {
            CurrentIndentLevel = 0,
            IndentSpaces = 4,
            OmitNullProperties = true
        };
    
        internal ExceptionOptions(ExceptionOptions options, int currentIndent)
        {
            this.CurrentIndentLevel = currentIndent;
            this.IndentSpaces = options.IndentSpaces;
            this.OmitNullProperties = options.OmitNullProperties;
        }
    
        internal string Indent { get { return new string(' ', this.IndentSpaces * this.CurrentIndentLevel); } }
    
        internal int CurrentIndentLevel { get; set; }
    
        public int IndentSpaces { get; set; }
    
        public bool OmitNullProperties { get; set; }
    }
    

    Top Tip - Logging Exceptions

    Most people will be using this code for logging. Consider using Serilog with my Serilog.Exceptions NuGet package which also logs all properties of an exception but does it faster and without reflection in the majority of cases. Serilog is a very advanced logging framework which is all the rage at the time of writing.

    Top Tip - Human Readable Stack Traces

    You can use the Ben.Demystifier NuGet package to get human readable stack traces for your exceptions or the serilog-enrichers-demystify NuGet package if you are using Serilog. If you are using .NET Core 2.1, then this feature comes built in.

    0 讨论(0)
  • 2021-01-30 11:13

    Each left-side name is property in the Exception. If you want to display Message field, you can do

    return ex.Message;
    

    Pretty simple. Likewise, the StackTrace can be displayed as below link.

    A complete example of StackTrace: http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx

    and Exception class: http://msdn.microsoft.com/en-us/library/system.exception.aspx

    0 讨论(0)
  • 2021-01-30 11:17

    There is no secret method. You could probably just override the ToString() method and build the string you want.

    Things like ErrorCode and Message are just properties of the exception that you can add to the desired string output.


    Update: After re-reading your question and thinking more about this, Jason's answer is more likely what you are wanting. Overriding the ToString() method would only be helpful for exceptions that you created, not already implemented ones. It doesn't make sense to sub class existing exceptions just to add this functionality.

    0 讨论(0)
  • 2021-01-30 11:17

    In visual studio that sort of information can be outputted by a debugger visualizer.

    I assume that because it is possible to write your own debugger visualizer: http://msdn.microsoft.com/en-us/library/e2zc529c.aspx

    That in theory, if your can reverse engineer the built-in debugger visualizer for exceptions (if your can work out where they are stored) then you could use the same functionality.

    EDIT:

    Here is a post about where the debugger visualizers are kept: Where do I find Microsoft.VisualStudio.DebuggerVisualizers?

    You might be able to use it for your own purposes.

    0 讨论(0)
提交回复
热议问题