本文介绍了从 InnerException(s) 获取所有消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法编写一个 LINQ 风格的简写"代码来遍历所有级别的 InnerException(s) 抛出的异常?我更愿意就地编写它,而不是调用扩展函数(如下所示)或继承 Exception 类.

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 calling an extension function (as below) or inheriting the Exception class.

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 不提供可以处理层次结构的方法,只有集合.

Unfortunately LINQ doesn't offer methods that could process hierarchical structures, only collections.

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

I actually have some extension methods that could help do this. I don't have the exact code in hand but they're something like this:

// 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);
}

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

Then in this case you could do this to enumerate through the exceptions:

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

这篇关于从 InnerException(s) 获取所有消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 18:27