让我们假设一个特定的异常“SomeException”是异常堆栈的一部分,

因此,让我们假设ex.InnerException.InnerException.InnerException的类型是 “SomeException

是否有任何内置在C#中的API,它会尝试在异常堆栈来查找给定的异常类型?

示例:

SomeException someExp = exp.LocateExceptionInStack(typeof(SomeException));
有帮助吗?

解决方案

没有,我不相信有任何建立在做这件事的方式。这并不难,虽然写的:

public static T LocateException<T>(Exception outer) where T : Exception
{
    while (outer != null)
    {
        T candidate = outer as T;
        if (candidate != null)
        {
            return candidate;
        }
        outer = outer.InnerException;
    }
    return null;
}

如果您使用C#3你可以把一个扩展方法(只是使参数“这个例外外”),并使用它会更好:

SomeException nested = originalException.Locate<SomeException>();

(注意名称的缩短,以及 - 调整自己的口味:)

其他提示

这只是4行代码:

    public static bool Contains<T>(Exception exception)
        where T : Exception
    {
        if(exception is T)
            return true;

        return 
            exception.InnerException != null && 
            LocateExceptionInStack<T>(exception.InnerException);
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top