输出异常消息,包括LINQ的所有内部

时间:2011-10-11 15:11:30

标签: c# linq

是否可以通过LINQ输出抛出异常的所有错误消息,包括inners?

我实现了没有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);
}

3 个答案:

答案 0 :(得分:8)

Linq使用序列,即对象集合。 exception.InnerException层次结构是单个对象的嵌套实例。你在算法上做的事情本质上不是一个序列操作,并且不会被Linq方法所覆盖。

您可以定义一个探索层次结构的方法,并在找到对象时返回(产生)一系列对象,但这最终将与您当前用于探索深度的算法相同,尽管您可以选择对结果应用序列操作(Linq)。

答案 1 :(得分: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);
}

答案 2 :(得分:0)

在当前的.NET Framework中,这现在是可能的:

string RecursiveStackTrace(Exception ex)
    => $"{ex.Message}<br />{ex.StackTrace}{((ex.InnerException != null) ? $"<br /><br />{RecursiveStackTrace(ex.InnerException)}" : string.Empty)}";