Sometimes I want to search a chain of exceptions (caught->cause1->cause2…) for an exception of a particular type. This isn’t a difficult problem, but having a simple utility makes it easier:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class SearchCausesFor<T extends Throwable> { private Class<T> target; private SearchCausesFor ( Class<T> target ) { this.target = target; } public static <T extends Throwable> SearchCausesFor<T> SEARCH ( Class<T> target ) { if ( target == null ) throw new IllegalArgumentException ( "target is null" ); return new SearchCausesFor<T> ( target ); } public T IN ( Throwable source ) { if ( source == null ) return null; if ( target == null ) throw new IllegalStateException ( "target is null" ); if ( target.isInstance( source ) ) return target.cast(source); return IN ( source.getCause() ); } } |
It’s pretty easy to use:
1 2 3 4 5 6 7 8 9 |
try { ... // some code that throws an exception } catch ( RootExceptionType oops ) { ExceptionTypeIWant wanted = SearchCausesFor.SEARCH(ExceptionTypeIWant.class).IN(oops); if ( wanted != null ) // do something with wanted } |