Click here to Skip to main content
Click here to Skip to main content

Find your inner exception

, 12 Sep 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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

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)

Share

About the Author

John Simmons / outlaw programmer
Software Developer (Senior)
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.
 
My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

 
QuestionWhat is the error? PinmemberAmmar Amros15-Sep-13 6:09 
AnswerRe: What is the error? PinprofessionalPIEBALDconsult15-Sep-13 6:54 
GeneralRe: What is the error? PinmemberAmmar Amros15-Sep-13 8:11 
AnswerRe: What is the error? PinmemberJohn Simmons / outlaw programmer16-Sep-13 16:26 
SuggestionI like it ;) PinprofessionalPaw Jershauge12-Sep-13 23:19 
GeneralMy vote of 5 Pinmemberjohannesnestler12-Sep-13 5:57 
QuestionWhat about chain of inheritance PinmemberFred Flams12-Sep-13 2:45 
AnswerRe: What about chain of inheritance Pinmemberjohannesnestler12-Sep-13 5:56 
GeneralRe: What about chain of inheritance PinmemberFred Flams13-Sep-13 2:39 
GeneralRe: What about chain of inheritance PinprofessionalRichard Deeming18-Sep-13 6:06 
You could go a step further and use as instead.
 
If you're using .NET 4.0, you also need to take account of the AggregateException[^] class.
 
public static T FindInnerException<T>(this Exception ex) where T : Exception
{
    T result = ex as T;
    if (result != null) return result;
 
    Exception inner = ex.InnerException;
    if (inner != null)
    {
        result = inner.FindInnerException<T>();
        if (result != null) return result;
    }
    
    var agEx = ex as AggregateException;
    if (agEx != null && agEx.InnerExceptions.Count > 1)
    {
        // InnerException always returns the first item from InnerExceptions.
        foreach (Exception iex in agEx.InnerExceptions.Skip(1))
        {
            result = iex.FindInnerException<T>();
            if (result != null) return result;
        }
    }
 
    return null;
}



"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer


AnswerRe: What about chain of inheritance PinmemberJohn Simmons / outlaw programmer12-Sep-13 8:18 
GeneralRe: What about chain of inheritance PinmemberFred Flams13-Sep-13 2:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 12 Sep 2013
Article Copyright 2013 by John Simmons / outlaw programmer
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid