@ControllerAdvice异常处理与@ResponseStatus一起使用

Jan*_*tny 8 java spring spring-mvc

我有@ControllerAdvice类,它处理一组异常.我们还有一些其他例外,它们都带有@ResponseStatus注释注释.要结合这两种方法,我们使用博客文章中描述的技术:http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc,即ControllerAdvice我们Exception通过以下方式处理泛型:

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        // If the exception is annotated with @ResponseStatus rethrow it and let
        // the framework handle it - like the OrderNotFoundException example
        // at the start of this post.
        // AnnotationUtils is a Spring Framework utility class.
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
            throw e;

        // Otherwise setup and send the user to a default error-view.
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }
Run Code Online (Sandbox Code Playgroud)

它就像一个魅力,然而,使用这种技术会导致错误,以下文本出现在应用程序日志中:

2014-06-11 15:51:32.907 ERROR o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Failed to invoke @ExceptionHandler method: ...

这是由以下代码引起的ExceptionHandlerExceptionResolver:

try {
            if (logger.isDebugEnabled()) {
                logger.debug("Invoking @ExceptionHandler method: " + exceptionHandlerMethod);
            }
            exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception);
        }
        catch (Exception invocationEx) {
            logger.error("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx);
            return null;
        }
Run Code Online (Sandbox Code Playgroud)

有没有人知道如何正确地将这两种方法结合到异常处理中以避免日志中的错误?

谢谢,Jan

Chr*_* H. 0

问题是您抛出异常而不是返回ModelAndView. ResponseStatusExceptionResolver本质上,您正在尝试在您的班级中重新实现ControllerAdvice。您可以这样做(例如,通过复制/粘贴来自 的代码ResponseStatusExceptionResolver),但除了重复之外,该方法也是不完整的。Spring 还附带了DefaultHandlerExceptionResolver一些内置异常,这种方法可能无法正确处理这些异常。

Exception.class相反,我所做的并不是在我的班级中提供一个包罗万象的处理程序ControllerAdvice。我不知道这是否是最好的解决方案,但这是我所知道的最好的解决方案。