在嵌套异常中检查某个异常类型是否是原因(原因等)的最佳方式? [英] Best way to check whether a certain exception type was the cause (of a cause, etc ...) in a nested exception?

查看:145
本文介绍了在嵌套异常中检查某个异常类型是否是原因(原因等)的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一些JUnit测试,验证是否抛出类型为 MyCustomException 的异常。但是,这个异常被包含在其他异常中,例如多次。在InvocationTargetException中,它又被包装在一个RuntimeException中。



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

  
try {
doSomethingPotentiallyExceptional() ;
fail(预期出现异常);
} catch(RuntimeException e){
if(!e。
wasCausedBy (MyCustomException.class)
fail(例如);
}

我想避免调用 getCause()一些层深层次,类似的丑陋的工作环境,有更好的方法吗?



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



关闭:
OK ,我想真的没有得到一个实用程序的方法:-)感谢所有回复的人!

解决方案

你为什么要避免 getCause 。当然,您可以自己写一个执行任务的方法,例如:

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


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 times, e.g. in an InvocationTargetException, which in turn is wrapped in a RuntimeException.

What's the best way to determine whether MyCustomException somehow caused the exception that I actually catch? I would like to do something like this (see underlined):


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

I would like to avoid calling getCause() a few "layers" deep, and similar ugly work-arounds. Is there a nicer way?

(Apparently, Spring has NestedRuntimeException.contains(Class), which does what I want - but I'm not using Spring.)

CLOSED: OK, I guess there's really no getting around a utility method :-) Thanks to everybody who replied!

解决方案

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())
   );
}

这篇关于在嵌套异常中检查某个异常类型是否是原因(原因等)的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆