ExceptionHandler 不适用于 Throwable [英] ExceptionHandler doesn't work with Throwable
问题描述
我们是一个基于 Spring MVC 的 REST 应用程序.我正在尝试使用 ExceptionHandler 注释来处理所有错误和异常.
我有
@ExceptionHandler(Throwable.class)公共@ResponseBody 字符串 handleErrors() {返回错误";}
这在抛出异常时有效,并且对任何错误无效.
我使用的是 Spring 4.0.有什么解决办法吗?
与 ExceptionHandler#value()
属性所指示的相反
Class[] value() 默认 {};
和 @ExceptionHandler
仅用于处理 Exception
及其子类型.
Spring 使用 ExceptionHandlerExceptionResolver
来解析带注释的处理程序,使用以下方法
doResolveHandlerMethodException(HttpServletRequest request,HttpServletResponse 响应、HandlerMethod handlerMethod、Exception 异常)
正如你所见,它只接受一个 Exception
.
您无法使用此配置使用 @ExceptionHandler
处理 Throwable
或 Error
类型.
我会告诉你提供你自己的 HandlerExceptionResolver
实现来处理 Throwable
实例,但你需要提供你自己的 DispatcherServlet
(以及大部分 MVC 堆栈)您自己,因为 DispatcherServlet
不会在任何可以产生重大影响的地方 catch
Throwable
实例.><小时>
更新:
自 4.3 起,Spring MVC 将抛出的 Throwable
值包装在 NestedServletException
实例中,并将其暴露给 ExceptionHandlerExceptionResolver
.
Ours is a Spring MVC based REST application. I am trying to use ExceptionHandler annotation to handle all errors and exceptions.
I have
@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.
I am using Spring 4.0. Is there any work-around?
Contrary to what the ExceptionHandler#value()
attribute indicates
Class<? extends Throwable>[] value() default {};
and @ExceptionHandler
is only meant to handle Exception
and its sub types.
Spring uses ExceptionHandlerExceptionResolver
to resolve your annotated handlers, using the following method
doResolveHandlerMethodException(HttpServletRequest request,
HttpServletResponse response, HandlerMethod handlerMethod, Exception exception)
which as you can see only accepts an Exception
.
You cannot handle Throwable
or Error
types with @ExceptionHandler
with this configuration.
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.
Update:
Since 4.3, Spring MVC wraps a thrown Throwable
value in a NestedServletException
instance and exposes that to the ExceptionHandlerExceptionResolver
.
这篇关于ExceptionHandler 不适用于 Throwable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!