c# - 从 InnerException 获取所有消息?

标签 c# c#-4.0

有什么方法可以编写 LINQ 样式的“速记”代码来遍历抛出异常的所有级别的 InnerException 吗?我更愿意就地编写它,而不是调用扩展函数(如下所示)或继承 Exception 类。

static class Extensions
{
    public static string GetaAllMessages(this Exception exp)
    {
        string message = string.Empty;
        Exception innerException = exp;

        do
        {
            message = message + (string.IsNullOrEmpty(innerException.Message) ? string.Empty : innerException.Message);
            innerException = innerException.InnerException;
        }
        while (innerException != null);

        return message;
    }
}; 

最佳答案

不幸的是,LINQ 不提供可以处理层次结构的方法,只提供集合。

我实际上有一些扩展方法可以帮助做到这一点。我手头没有确切的代码,但它们是这样的:

// all error checking left out for brevity

// a.k.a., linked list style enumerator
public static IEnumerable<TSource> FromHierarchy<TSource>(
    this TSource source,
    Func<TSource, TSource> nextItem,
    Func<TSource, bool> canContinue)
{
    for (var current = source; canContinue(current); current = nextItem(current))
    {
        yield return current;
    }
}

public static IEnumerable<TSource> FromHierarchy<TSource>(
    this TSource source,
    Func<TSource, TSource> nextItem)
    where TSource : class
{
    return FromHierarchy(source, nextItem, s => s != null);
}

那么在这种情况下,您可以这样做来枚举异常:

public static string GetaAllMessages(this Exception exception)
{
    var messages = exception.FromHierarchy(ex => ex.InnerException)
        .Select(ex => ex.Message);
    return String.Join(Environment.NewLine, messages);
}

关于c# - 从 InnerException 获取所有消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9314172/

相关文章:

c# - Entity Framework 按日期选择每个组中的一个

c# - 在asp.net和java之间共享 session 变量

.net - Font.Color 返回令人困惑的值

c#-4.0 - 取消订阅用户控件中的事件的标准方法

asp.net - MVC 3 搜索路径

c# - 我怎样才能让我的 trie 更有效率?

c# - 如何从 linq 或 IQueryable 对象获取可执行的 sql 语句?

c# - 使用 Servicestack.Text 进行 XML 反序列化

c# - 以编程方式安排/创建 Skype for Business session

css - 如何为单选按钮制作标签