我认为你不能使用开箱即用的 Spring 来做到这一点。如果你深入了解这个方法ExceptionHandlerExceptionResolver#doResolveHandlerMethodException,你可以看到一开始 Spring 正在寻找 single 方法来处理发生的异常:
...
ServletInvocableHandlerMethod exceptionHandlerMethod = getExceptionHandlerMethod(handlerMethod, exception);
if (exceptionHandlerMethod == null) {
return null;
}
...
你也可以看看getExceptionHandlerMethod方法的实现。首先它试图在你的控制器方法中找到合适的处理程序,如果没有找到 - 然后在控制器顾问中。
之后它会调用它:
try {
if (logger.isDebugEnabled()) {
logger.debug("Invoking @ExceptionHandler method: " + exceptionHandlerMethod);
}
exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, handlerMethod);
}
catch (Exception invocationEx) {
if (logger.isErrorEnabled()) {
logger.error("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx);
}
return null;
}
您还应该注意,Spring 会吞下原始异常处理期间可能发生的任何异常,因此您甚至不能从第一个处理程序中抛出新异常或重新抛出原始异常,以便可以在其他地方捕获它(实际上可以,但是这是毫无意义的)。
所以,如果你真的想这样做 - 我想唯一的方法是写你自己的ExceptionHandlerExceptionResolver(可能扩展 Springs ExceptionHandlerExceptionResolver)并修改 doResolveHandlerMethodException 方法,所以它寻找乘法exceptionHandlerMethod(一个在控制器中,一个在顾问中)并在链中调用它。这可能很棘手:)
另外,您可以查看this Jira 票证。
希望对你有帮助。