从不调用控制器中的Spring MVC @ExceptionHandler方法

111*_*01b 14 java rest spring-mvc

我有一个Spring MVC控制器,带有一些简单的REST服务请求.我想在从我的服务中抛出特定异常时添加一些错误处理,但是我无法获得一个用@ExceptionHandler注释的处理程序方法来实际调用它.这是一个服务我故意抛出异常来尝试让我的处理程序方法接管.永远不会调用处理程序方法,Spring只会向调用客户端返回500错误.你对我做错了什么有什么想法吗?

@ExceptionHandler(IOException.class)
public ModelAndView handleIOException(IOException ex, HttpServletRequest request, HttpServletResponse response) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
    System.out.println("It worked!");
    return new ModelAndView();
}

@RequestMapping(value = "/json/remove-service/{id}", method = RequestMethod.DELETE)
public void remove(@PathVariable("id") Long id) throws IOException {
    throw new IOException("The handler should take over from here!");
}
Run Code Online (Sandbox Code Playgroud)

che*_*tts 13

Spring论坛上的这个提示可能会对你有帮助.

您可能已DispatchServlet在webmvc-servlet.xml文件中为您配置了bean (*-servlet.xml文件的名称可能不同)

如果XML文件已经包含另一个ExceptionResolver(就像SimpleMappingExceptionResovlerSpring不会自动为你添加任何其他解析器.所以手动添加注释解析器如下:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver" />
Run Code Online (Sandbox Code Playgroud)

应该启用@HandlerException处理.

  • 现在不推荐使用`AnnotationMethodHandlerExceptionResolver`,因此这对于较新版本的Spring没有帮助. (3认同)

Mat*_*man 12

令人沮丧的是,我也遭受了这种痛苦.我发现如果你错误地实现Throwable而不是ExceptionException解析器只会重新抛出你ThrowableIllegalStateException.这将无法调用您的@ExceptionHandler.

如果您已实施Throwable而不是Exception尝试将其更改为Exception.

这是有问题的代码 InvocableHandlerMethod

catch (InvocationTargetException e) {
            // Unwrap for HandlerExceptionResolvers ...
            Throwable targetException = e.getTargetException();
            if (targetException instanceof RuntimeException) {
                throw (RuntimeException) targetException;
            }
            else if (targetException instanceof Error) {
                throw (Error) targetException;
            }
            else if (targetException instanceof Exception) {
                throw (Exception) targetException;
            }
            else {
                String msg = getInvocationErrorMessage("Failed to invoke controller method", args);
                throw new IllegalStateException(msg, targetException);
            }
        }
Run Code Online (Sandbox Code Playgroud)