gpt4 book ai didi

java - 检查某个异常类型是否是嵌套异常中的原因(原因等)的最佳方法?

转载 作者:IT老高 更新时间:2023-10-28 13:47:52 24 4
gpt4 key购买 nike

我正在编写一些 JUnit 测试来验证 MyCustomException 类型的异常是否被抛出。但是,此异常多次包含在其他异常中,例如在 InvocationTargetException 中,而后者又被包装在 RuntimeException 中。

确定 MyCustomException 是否以某种方式导致我实际捕获的异常的最佳方法是什么?我想做这样的事情(见下划线):


try {
doSomethingPotentiallyExceptional();
fail("Expected an exception.");
} catch (RuntimeException e) {
if (!e.
wasCausedBy(MyCustomException.class)
fail("Expected a different kind of exception.");
}

我想避免调用 getCause() 一些“层”深,以及类似的丑陋变通办法。有更好的方法吗?

显然,Spring 有 NestedRuntimeException.contains(Class) ,这是我想要的 - 但我没有使用 Spring。

最佳答案

如果您使用 Apache Commons Lang ,那么您可以使用以下内容:

(1) 原因应完全属于指定类型时

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

(2) 当原因应该是指定类型或其子类类型时

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

关于java - 检查某个异常类型是否是嵌套异常中的原因(原因等)的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/610628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com