在spring项目中,我有个service会通过method.invoke()调用业务方法,业务方法可能会抛出一些自定义的异常,但是实际运行的时候,自定义异常会被java.lang.reflect.InvocationTargetException包裹上,导致GlobalExceptionHandler无法匹配。请问要如何取消这种包裹
代码示例:
```java
public void test1() throws NoSuchMethodException {
Method method = this.getClass().getDeclaredMethod("test2");
try {
method.invoke(this);
}catch (Exception ex){
System.out.print(ex.getMessage());
}
}
private void test2(){
throw new RuntimeException("111111");
}
test2中抛出的异常在test1中变成了java.lang.reflect.InvocationTargetException。其中ex.target才是我抛出的异常。
用debug方式跟踪,在throw 之后,跳到了org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(Object... args),其中抛出的异常被捕捉,而后再次抛出,但是被捕捉的异常已经被包裹了一次,此时的RuntimeException被包裹了两层InvocationTargetException
