ExceptionHandler不适用于Throwable

l a*_*a s 4 java rest tomcat web-applications spring-mvc

我们是一个基于Spring MVC的REST应用程序.我试图使用ExceptionHandler注释来处理所有错误和异常.

我有

    @ExceptionHandler(Throwable.class)
    public @ResponseBody String handleErrors() {
        return "error";
    }
Run Code Online (Sandbox Code Playgroud)

只要抛出异常并且它不适用于任何错误,它就可以工作.

我使用的是Spring 4.0.有没有解决方法?

Sot*_*lis 6

ExceptionHandler#value()属性指示的相反

Class<? extends Throwable>[] value() default {};
Run Code Online (Sandbox Code Playgroud)

并且@ExceptionHandler仅用于处理Exception及其子类型.

Spring使用ExceptionHandlerExceptionResolver以下方法来解析带注释的处理程序

doResolveHandlerMethodException(HttpServletRequest request,
        HttpServletResponse response, HandlerMethod handlerMethod, Exception exception) 
Run Code Online (Sandbox Code Playgroud)

你可以看到只接受一个Exception.

你不能处理ThrowableError类型与@ExceptionHandler此配置.

我会告诉你提供自己的HandlerExceptionResolver 实现来处理Throwable实例,但你需要自己提供自己的DispatcherServlet(和大多数MVC堆栈),因为在任何你可以产生重大差异的地方DispatcherServlet没有catch Throwable实例.


更新:

从4.3开始,Spring MVC Throwable在一个NestedServletException实例中包含一个抛出的值并将其暴露给ExceptionHandlerExceptionResolver.

  • @SotiriosDelimanolis我完全同意,但imho认为这是Spring的严重限制.处理所有`Throwable`实例的一个合法案例是自定义日志记录. (3认同)