2011-10-11 60 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); 
}