rest - 在部署在 Tomcat 中的 Spring 启动应用程序中,没有从 @ExceptionHandler 返回 @ResponseBody

标签 rest spring-mvc tomcat spring-boot exceptionhandler

我有一个 Spring Boot Web 应用程序,它在 STS 中运行良好,但在 Tomcat 中从 WAR 文件运行时表现出不同的行为。

我使用 Thymeleaf 来处理我所有的网页,但我有几个页面使用 jQuery 发送异步调用并使用户体验更加动态。

无论如何,我有一个调用服务方法的 Controller 方法,该方法可能会抛出一个 RuntimeException,我是这样处理的:

@ExceptionHandler(MyRuntimeException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody String handleMyRuntimeException(MyRuntimeException exception) {
    return "Oops an error happened : " + exception.getMessage();
}

在 JS 中,我使用上面返回的响应主体在屏幕上显示消息。

当我在 STS 中运行我的应用程序时,它工作得很好,但是一旦我切换到将它部署在 Tomcat 中,就会调用 ErrorPageFilter 并且在 doFilter() 中它会:

if (status >= 400) {
    handleErrorStatus(request, response, status, wrapped.getMessage());
    response.flushBuffer();
}

handleErrorStatus() 中,它会创建一个带有状态和相关消息的错误,但不会返回我的响应。

我还没有想出如何解决这个问题,如果有人能提供帮助,我将不胜感激。

谢谢!

最佳答案

我通过执行以下操作解决了这个问题(我认为这是一个 Spring Boot 问题)。

  1. 分离 Rest 和 Mvc Controller 在这里查看我的问题:Spring MVC: Get i18n message for reason in @RequestStatus on a @ExceptionHandler

  2. 注入(inject) Jackson 转换器并自己编写响应:

    @ControllerAdvice(annotations = RestController.class)
    @Priority(1)
    @ResponseBody
    public class RestControllerAdvice {
        @Autowired
        private MappingJackson2HttpMessageConverter jacksonMessageConverter;
    
        @ExceptionHandler(RuntimeException.class)
        @ResponseStatus(value = HttpStatus.BAD_REQUEST)
        public void handleRuntimeException(HttpServletRequest request, HttpServletResponse response, RuntimeException exception) {
            try {
                jacksonMessageConverter.write(new MyRestResult(translateMessage(exception)), MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
                response.flushBuffer(); // Flush to commit the response
                } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

关于rest - 在部署在 Tomcat 中的 Spring 启动应用程序中,没有从 @ExceptionHandler 返回 @ResponseBody,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29075160/

相关文章:

eclipse - 请求的资源不可用。 Apache Tomcat/7.0.42

java.lang.NoClassDefFoundError : com/twilio/sdk/TwilioRestClient

c# - WebAPI 和 Angular JS Excel 文件下载 - 文件已损坏

java - 使用 Spring Boot 的 Spring MVC WebApp 无法启动 "*.jsp"文件

apache - 在 jetty 中使用 tomcat Trust-store 进行 SSL

java - 来自用户的 Apache Tomcat 服务器屏蔽过程

bash - curl: 没有为 restful api 指定 URL

java - SocketTimeoutException cxf httpconduit PUT

java - Hibernate 查询上的链接 setParameter

java - 在 Spring Security 中使用自定义过滤器时,Spring 单元测试 MockMvc 失败