문제
특정 예외를 가정 해 봅시다. "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);
}
제휴하지 않습니다 StackOverflow