ExceptionHandler不适用于Throwable [英] ExceptionHandler doesn't work with Throwable
问题描述
我们是一个基于Spring MVC的REST应用程序。我试图使用ExceptionHandler注释来处理所有错误和异常。
Ours is a Spring MVC based REST application. I am trying to use ExceptionHandler annotation to handle all errors and exceptions.
我有
@ExceptionHandler(Throwable.class)
public @ResponseBody String handleErrors() {
return "error";
}
只要抛出异常并且它不适用于任何错误。
This works whenever there is an exception thrown and it doesn't work for any errors.
我使用的是Spring 4.0。是否有任何解决方法?
I am using Spring 4.0. Is there any work-around?
推荐答案
与 ExceptionHandler#value()$相反c $ c>属性表示
Class<? extends Throwable>[] value() default {};
和 @ExceptionHandler
仅用于处理 Exception
及其子类型。
and @ExceptionHandler
is only meant to handle Exception
and its sub types.
Spring使用 ExceptionHandlerExceptionResolver
使用以下方法解析带注释的处理程序
Spring uses ExceptionHandlerExceptionResolver
to resolve your annotated handlers, using the following method
doResolveHandlerMethodException(HttpServletRequest request,
HttpServletResponse response, HandlerMethod handlerMethod, Exception exception)
您可以看到只接受异常
。
您无法处理 Throwable
或错误
具有此配置的 @ExceptionHandler
的类型。
You cannot handle Throwable
or Error
types with @ExceptionHandler
with this configuration.
我会告诉您提供自己的 HandlerExceptionResolver
实现它处理 Throwable
实例,但你需要提供自己的 DispatcherServlet
(以及大多数MVC堆栈)自 DispatcherServlet
不会 catch
可以在任何可能产生重大差异的地方投掷
个实例。
I would tell you to provide your own HandlerExceptionResolver
implementation which does handle Throwable
instances, but you'd need to provide your own DispatcherServlet
(and most of the MVC stack) yourself since DispatcherServlet
does not catch
Throwable
instances at any place where you could make any significant difference.
更新:
自4.3以来,Spring MVC包装抛出
值,并将其暴露给 NestedServletException
实例中的可抛出 ExceptionHandlerExceptionResolver
。
Since 4.3, Spring MVC wraps a thrown Throwable
value in a NestedServletException
instance and exposes that to the ExceptionHandlerExceptionResolver
.
这篇关于ExceptionHandler不适用于Throwable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!