ExceptionHandler不适用于Throwable [英] ExceptionHandler doesn't work with Throwable

查看:308
本文介绍了ExceptionHandler不适用于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()属性表示

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆