2011-10-11 64 views
4

是否可以通過LINQ輸出拋出的異常(包括inners)的所有錯誤消息?輸出異常消息,包括LINQ中的所有內容

我實現了沒有LINQ的功能,但我想要更簡潔的代碼。 (是不是LINQ的目的是什麼?)

我沒有LINQ代碼如下:

try { 
    ... 
} catch (Exception ex) { 
    string msg = "Exception thrown with message(s): "; 
    Exception curEx= ex; 
    do { 
     msg += string.Format("\n {0}", curEx.Message); 
     curEx = curEx.InnerException; 
    } while (curEx != null); 
    MessageBox.Show(msg); 
} 
+2

由於LINQ工作在序列你必須建立你自己的函數返回一系列異常,然後使用LINQ。 查找'yield'關鍵字。 –

+0

謝謝,類似Anthony Pegram的回答。但我的代碼不會更簡潔,如果我使用yield:( – sergtk

回答

8

LINQ的工作在序列,即對象的集合。 exception.InnerException層次結構是嵌套的單個對象的實例。算法上你在做什麼並不是一種固有的序列操作,並且Linq方法不會涵蓋。

您可以定義一個方法來探索層次結構,並在找到它們時返回(產生)一系列對象,但這最終將與您當前用於探索深度的算法相同,儘管您可以然後選擇對結果應用序列操作(Linq)。

+1

)感謝!可以應用LINQ的優秀解釋。LINQ對我來說是新的 – sergtk

2

要在@Anthony Pegram的回答跟進,你可以定義一個擴展方法來獲取內部異常的序列:

public static class ExceptionExtensions 
{ 
    public static IEnumerable<Exception> GetAllExceptions(this Exception ex) 
    { 
     List<Exception> exceptions = new List<Exception>() {ex}; 

     Exception currentEx = ex; 
     while (currentEx.InnerException != null) 
     { 
      currentEx = currentEx.InnerException; 
      exceptions.Add(currentEx); 
     } 

     return exceptions; 
    } 
} 

那麼你就可以使用LINQ的序列。如果我們有一個拋出嵌套異常這樣的方法:

public static class ExceptionThrower { 
    public static void ThisThrows() { 
     throw new Exception("ThisThrows"); 
    } 

    public static void ThisRethrows() { 
     try { 
      ExceptionThrower.ThisThrows(); 
     } 
     catch (Exception ex) { 
      throw new Exception("ThisRetrows",ex); 
     } 
    } 
} 

這裏是你如何使用LINQ與我們創建的小擴展方法:

try { 
    ExceptionThrower.ThisRethrows(); 
} 
catch(Exception ex) { 
    // using LINQ to print all the nested Exception Messages 
    // separated by commas 
    var s = ex.GetAllExceptions() 
    .Select(e => e.Message) 
    .Aggregate((m1, m2) => m1 + ", " + m2); 

    Console.WriteLine(s); 
}