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

后端 未结 8 1274
误落风尘
误落风尘 2021-02-03 21:05

I am writing some JUnit tests that verify that an exception of type MyCustomException is thrown. However, this exception is wrapped in other exceptions a number of

相关标签:
8条回答
  • 2021-02-03 21:36

    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())
       );
    }
    
    0 讨论(0)
  • 2021-02-03 21:41

    Based on Patrick Boos answer: If you using Apache Commons Lang 3 you can check:

    indexOfThrowable: Returns the (zero based) index of the first Throwable that matches the specified class (exactly) in the exception chain. Subclasses of the specified class do not match

    if (ExceptionUtils.indexOfThrowable(e, clazz) != -1) {
        // your code
    }
    

    or

    indexOfType: Returns the (zero based) index of the first Throwable that matches the specified class or subclass in the exception chain. Subclasses of the specified class do match

    if (ExceptionUtils.indexOfType(e, clazz) != -1) {
        // your code
    }
    

    Example for multiple types with Java 8:

    Class<? extends Throwable>[] classes = {...}
    boolean match = Arrays.stream(classes)
                .anyMatch(clazz -> ExceptionUtils.indexOfType(e, clazz) != -1);
    
    0 讨论(0)
提交回复
热议问题