泛型@ExceptionHandler和DefaultHandlerExceptionResolver可以很好用吗?

时间:2015-03-22 10:20:13

标签: spring-mvc

我希望实现一个@ExceptionHandler,以防止所有未捕获的异常进入客户端。像这样......

@ControllerAdvice
public class ExceptionHandlingControllerAdvice {

    private static final Logger logger = getLogger(ExceptionHandlingControllerAdvice.class);

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = INTERNAL_SERVER_ERROR)
    public void handleAnyUncaughtException(Exception e) {
        logger.error("This uncaught exception is being blocked from reaching the client.", e);
    }
}

但这会妨碍DefaultHandlerExceptionResolver开箱即用的异常处理,例如在使用@RequestBody检查失败的@Valid验证时抛出4xx错误。似乎@ExceptionHandler优先,在DHER尝试返回4xx之前返回500.

有没有办法阻止未捕获的异常进入客户端,但仍然允许DefaultHandlerExceptionResolver完成其工作?

1 个答案:

答案 0 :(得分:4)

我找到了解决方案。我正在编写一个显式处理所有标准Spring MVC异常的@ExceptionHandler,检查列表的manual,并遍历ResponseEntityExceptionHandler基类。

@ControllerAdvice中扩展该基类会为标准例外添加@ExceptionHandler,但如果这些例外发生变化,则必须维护列表。 @ControllerAdvice现在看起来像这样。

@ControllerAdvice
public class ExceptionHandlingControllerAdvice extends ResponseEntityExceptionHandler {

    private static final Logger logger = getLogger(ExceptionHandlingControllerAdvice.class);

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = INTERNAL_SERVER_ERROR)
    public void handleAnyUncaughtException(Exception e) {
        logger.error("This uncaught exception is being blocked from reaching the client.", e);
    }
}