如何在Exception堆栈中查找特定异常

nmd*_*mdr 2 c# api logic exception

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

所以让我们假设ex.InnerException.InnerException.InnerException是" SomeException" 的类型

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

例:

SomeException someExp = exp.LocateExceptionInStack(typeof(SomeException));
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

不,我不相信有任何内置的方式.虽然写起来并不难:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果你正在使用C#3,你可以使它成为一个扩展方法(只需将参数设置为"此异常外部"),使用它会更好:

SomeException nested = originalException.Locate<SomeException>();
Run Code Online (Sandbox Code Playgroud)

(注意缩短名称 - 根据自己的喜好调整:)