在spring boot中通过@Aspect拦截处理时候,发现抛出的异常总是显示的是java.lang.reflect.UndeclaredThrowableException异常,跟自己捕捉抛出的不一致,通过debug发现,抛出的异常最后会在CgligAopProxy的proceed()方法中进行判断:
@Override
@Nullable
public Object proceed() throws Throwable {
try {
return super.proceed();
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
if (ReflectionUtils.declaresException(getMethod(), ex.getClass()) ||
KotlinDetector.isKotlinType(getMethod().getDeclaringClass())) {
// Propagate original exception if declared on the target method
// (with callers expecting it). Always propagate it for Kotlin code
// since checked exceptions do not have to be explicitly declared there.
throw ex;
}
else {
// Checked exception thrown in the interceptor but not declared on the
// target method signature -> apply an UndeclaredThrowableException,
// aligned with standard JDK dynamic proxy behavior.
throw new UndeclaredThrowableException(ex);
}
}
}
关键在if (ReflectionUtils.declaresException(getMethod(), ex.getClass()) || KotlinDetector.isKotlinType(getMethod().getDeclaringClass())) { throw ex;}
这里,判断的是切点处是否显式抛出该类异常,是的话,抛出传播否则抛出throw new UndeclaredThrowableException(ex)
因此,在切面抛出的异常,在切点处也需要显式抛出。