Monday, April 25, 2011

How to locate a particular exception in a Exception stack

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));
From stackoverflow
  • 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 :)

  • 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);
        }
    
    Pontus Gagge : If it's supposed to do recursion, you might want to determine whether to call it Contains or LocateExceptionInStack...

0 comments:

Post a Comment