Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Find your inner exception

4.83/5 (6 votes)
12 Sep 2013CPOL 45.4K  
One approach to find a specific exception type inside the containing exception

Introduction

We have some code that uses CSLA, and in the process of manipulating the database, an exception is being thrown that we handle via a custom exception. In some cases, CSLA leaves the thrown exception alone, but in others, it decorates the exceptions message something like this: "DataPortal_Fetch.Error blah blah blah:OUR INTENDED MESSAGE HERE: stack trace info". After spending 30 minutes trying (and failing) to finger out where this decoration was happening, I came up with the following solution.


The Code

I create this extension method for the Exception class:

C#
public static class ExceptionExtension
{
    public static T FindInnerException<T>(this Exception ex) where T : Exception
    {
        if (!ex.GetType().Equals(typeof(T)))
        {
            Exception inner = ex.InnerException;
            if (inner == null)
            {
                return null;
            }
            else
            {
                if (inner.GetType().Equals(typeof(T)))
                {
                    return (T)inner;
                }
                else
                {
                    return inner.FindInnerException<T>();
                }
            }
        }
        else
        {
            return (T)ex;
        }
    }
}

It's pretty simple really. The code is looking for the first exception in the chain for the specified exception type. If the end of the chain is reached before finding the desired type, the method returns null. If it finds the desired type, it returns the exception it found.

NOTE: Fred Flams posted a comment with a modification that makes the code a little more versatile. Make sure you check it out. What about chain of inheritance[^]

Usage

C#
try
{
    // do something that could throw your custom exception
}
catch (Exception ex)
{
    MyCustomException myEx = ex.FindInnerException<MyCustomException>();
    if (myEx != null)
    {
        // do something with the exception
    }
}

History

  • Original Creation: 09/11/2013

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)