我有一个 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 问题)。
分离 Rest 和 Mvc Controller 在这里查看我的问题:Spring MVC: Get i18n message for reason in @RequestStatus on a @ExceptionHandler
注入(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/