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

后端 未结 8 1276
误落风尘
误落风尘 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:24

    Well, I think there's no way to do this without calling getCause(). It you think it's ugly implement a utility class for doing this:

    public class ExceptionUtils {
         public static boolean wasCausedBy(Throwable e, Class) {
             // call getCause() until it returns null or finds the exception
         }
    }
    

提交回复
热议问题