Getting all messages from InnerException(s)?

前端 未结 12 601
闹比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:02

    LINQ is generally used to work with collections of objects. However, arguably, in your case there is no collection of objects (but a graph). So even though some LINQ code might be possible, IMHO it would be rather convoluted or artificial.

    On the other hand, your example looks like a prime example where extension methods are actually reasonable. Not to speak of issues like reuse, encapsulation, etc.

    I would stay with an extension method, although I might have implemented it that way:

    public static string GetAllMessages(this Exception ex)
    {
       if (ex == null)
         throw new ArgumentNullException("ex");
    
       StringBuilder sb = new StringBuilder();
    
       while (ex != null)
       {
          if (!string.IsNullOrEmpty(ex.Message))
          {
             if (sb.Length > 0)
               sb.Append(" ");
    
             sb.Append(ex.Message);
          }
    
          ex = ex.InnerException;
       }
    
       return sb.ToString();
    }
    

    But that is largely an issue of taste.

提交回复
热议问题