Spring全局异常处理如何根据条件返回JSON或Thymeleaf模板页
解决方案
核心思路是移除方法上强制返回响应体的@ResponseBody注解,通过返回不同类型的结果让Spring自动匹配处理逻辑:
- 返回字符串类型时,Spring会将其作为视图名交由Thymeleaf视图解析器渲染
- 返回自定义业务异常对象时,Spring会自动通过消息转换器序列化为JSON响应
修改后的代码示例
@ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Object constraintViolation(final Throwable throwable) { // 匹配需要返回HTML错误页的场景 if (throwable.getMessage().startsWith("change")){ // 直接返回视图名,走Thymeleaf渲染逻辑 return "400"; } // 提取错误信息 String errMsg = throwable.getMessage().replaceAll(".*\\s?:\\s?(.*)$", "$1"); // 直接返回异常对象,自动序列化为JSON return new RestApiException(1007, errMsg); }
可选的手动处理方案(适用更复杂场景)
如果需要更精细的控制,也可以直接操作请求响应对象手动处理返回内容:
@ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public void constraintViolation(HttpServletRequest request, HttpServletResponse response, final Throwable throwable) throws IOException { if (throwable.getMessage().startsWith("change")){ // 转发到400页面对应的映射地址 request.getRequestDispatcher("/400").forward(request, response); return; } String errMsg = throwable.getMessage().replaceAll(".*\\s?:\\s?(.*)$", "$1"); RestApiException apiException = new RestApiException(1007, errMsg); // 手动写入JSON响应 response.setContentType("application/json;charset=utf-8"); response.getWriter().write(new ObjectMapper().writeValueAsString(apiException)); }
注意事项
- 不要对返回的
RestApiException调用toString()方法,直接返回对象本身才能被正确序列化为JSON结构 - Spring Boot项目默认自带JSON序列化转换器,无需额外配置即可支持对象转JSON响应
内容的提问来源于stack exchange,提问作者koa73
相关产品推荐
相关产品推荐

