Getting all messages from InnerException(s)?

前端 未结 12 718
闹比i
闹比i 2020-12-02 07:13

Is there any way to write a LINQ style \"short hand\" code for walking to all levels of InnerException(s) of Exception thrown? I would prefer to write it in place instead of

12条回答
  •  忘掉有多难
    2020-12-02 08:12

    Most solutions presended here have the following implementation errors:

    • handle null exceptions
    • handle the inner exceptions of AggregateException
    • define a max depth for recurse inner exceptions (ie. with circular dependencies)

    A better implementation is this here:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    public static string AggregateMessages(this Exception ex) =>
        ex.GetInnerExceptions()
            .Aggregate(
                new StringBuilder(),
                (sb, e) => sb.AppendLine(e.Message),
                sb => sb.ToString());
    
    public static IEnumerable GetInnerExceptions(this Exception ex, int maxDepth = 5)
    {
        if (ex == null || maxDepth <= 0)
        {
            yield break;
        }
    
        yield return ex;
    
        if (ex is AggregateException ax)
        {
            foreach(var i in ax.InnerExceptions.SelectMany(ie => GetInnerExceptions(ie, maxDepth - 1)))
                yield return i;
        }
    
        foreach (var i in GetInnerExceptions(ex.InnerException, maxDepth - 1))
            yield return i;
    }
    

    Example usage:

    try
    {
        // ...
    }
    catch(Exception e)
    {
        Log.Error(e, e.AggregateMessages());
    }
    

提交回复
热议问题