How to locate a particular exception in a Exception stack
Question
Let us assume that a particular Exception "SomeException
" is part of the exception stack,
so let us assume ex.InnerException.InnerException.InnerException
is of type "SomeException
"
Is there any built-in API in C# which will try to locate a given exception type in exception stack?
Example:
SomeException someExp = exp.LocateExceptionInStack(typeof(SomeException));
Solution
No, I don't believe there's any built in way of doing it. It's not hard to write though:
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;
}
If you're using C# 3 you could make it an extension method (just make the parameter "this Exception outer") and it would be even nicer to use:
SomeException nested = originalException.Locate<SomeException>();
(Note the shortening of the name as well - adjust to your own taste :)
OTHER TIPS
It's just 4 lines of code:
public static bool Contains<T>(Exception exception)
where T : Exception
{
if(exception is T)
return true;
return
exception.InnerException != null &&
LocateExceptionInStack<T>(exception.InnerException);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow