让我们假设一个特定的异常“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>();
(请注意名称的缩写 - 根据您自己的口味调整 :)
关于c# - 如何在异常堆栈中定位特定异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/661838/