让我们假设一个特定的异常“ 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,则可以将其设为扩展方法(只需将参数设为“this Exception outer”),使用起来会更好:
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);
}