Best way to check whether a certain exception type was the cause (of a cause, etc ...) in a nested exception? Best way to check whether a certain exception type was the cause (of a cause, etc ...) in a nested exception? spring spring

Best way to check whether a certain exception type was the cause (of a cause, etc ...) in a nested exception?


If you are using Apache Commons Lang, then you can use the following:

(1) When the cause should be exactly of the specified type

if (ExceptionUtils.indexOfThrowable(exception, ExpectedException.class) != -1) {    // exception is or has a cause of type ExpectedException.class}

(2) When the cause should be either of the specified type or its subclass type

if (ExceptionUtils.indexOfType(exception, ExpectedException.class) != -1) {    // exception is or has a cause of type ExpectedException.class or its subclass}


Why would you want to avoid getCause. You can, of course, write yourself a method to perform the task, something like:

public static boolean isCause(    Class<? extends Throwable> expected,    Throwable exc) {   return expected.isInstance(exc) || (       exc != null && isCause(expected, exc.getCause())   );}


I don't think you have any choice but to call through the layers of getCause. If you look at the source code for the Spring NestedRuntimeException that you mention that is how it is implemented.