4

我有一个 Spring Boot Web 应用程序,它从 STS 运行得很好,但从 WAR 文件在 Tomcat 中运行时显示不同的行为。

我使用 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()状态和相关消息中创建一个错误,但不返回我的响应。

我还没有弄清楚如何解决这个问题,如果有人可以提供帮助,我将不胜感激。

谢谢!

4

1 回答 1

2

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

  1. 单独的 Rest 和 Mvc 控制器在这里查看我的问题:Spring MVC: Get i18n message for reason in a @RequestStatus on a @ExceptionHandler

  2. 注入杰克逊转换器并自己写响应:

    @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();
            }
        }
    }
    
于 2015-03-27T08:33:16.290 回答