You need to loop, and for this you need to clear it to move the loop into a separate function.
I created an extension method to handle this. It returns a list of all internal exceptions of the specified type, with the exception Exception.InnerException and AggregateException.InnerExceptions.
In my particular problem, the pursuit of internal exceptions was more complicated than usual because the exceptions were thrown by the constructors of classes that were called through reflection. The exception we caught was an InnerException of type TargetInvocationException, and the exceptions that we really looked for were deeply immersed in the tree.
public static class ExceptionExtensions { public static IEnumerable<T> innerExceptions<T>(this Exception ex) where T : Exception { var rVal = new List<T>(); Action<Exception> lambda = null; lambda = (x) => { var xt = x as T; if (xt != null) rVal.Add(xt); if (x.InnerException != null) lambda(x.InnerException); var ax = x as AggregateException; if (ax != null) { foreach (var aix in ax.InnerExceptions) lambda(aix); } }; lambda(ex); return rVal; } }
The use is pretty simple. If, for example, you want to know if we met
catch (Exception ex) { var myExes = ex.innerExceptions<MyException>(); if (myExes.Any(x => x.Message.StartsWith("Encountered my specific error"))) {
Jeff Dege Mar 20 '17 at 17:16 2017-03-20 17:16
source share