@ControllerAdvice 全局异常响应页面和 JSON

我这里页面以 Thymeleaf 为例子,相关配置:

spring:
  thymeleaf:
    cache: false
    mode: HTML5
    encoding: UTF-8
    prefix: classpath:/templates/

判断是否是 AJAX:

public static boolean isAjaxRequest(HttpServletRequest request) {
  	return request.getHeader("x-requested-with") != null;
}

异常拦截器:

/**
 * @author Dongguabai
 * @Description
 * @Date 创建于 2020-12-02 10:43
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    private static final String ERROR_PAGE = "error";

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Object handleException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Exception e) throws UnsupportedEncodingException {
        if (isAjaxRequest(httpServletRequest)){
             //这里返回项目中自定义的统一响应对象即可
            return json(e);
        }
        return view(e);
    }

  这里返回项目中自定义的统一响应对象即可
    private ResponseX json(Exception e) {
        return new ResponseX();
    }
 
		//这里返回 ModelAndView 
    public ModelAndView view(Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setStatus(HttpStatus.BAD_REQUEST);
        modelAndView.setViewName(ERROR_PAGE);
        modelAndView.addObject("msg","msg");
        modelAndView.addObject("code","code");
        return modelAndView;
    }
}

error.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <head th:insert="fragments/header"/>
    <title>error</title>
</head>
<body>
  <span th:text="${code}" ></span> - <span th:text="${msg}" ></span>
</body>
</html>

这里补充说明下,建议不要使用拦截器做,当然不是说拦截器不行(处理响应流即可),主要是拦截器其实是无法处理 Controller 中的异常的:

org.springframework.web.servlet.DispatcherServlet#triggerAfterCompletion

    private void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, @Nullable HandlerExecutionChain mappedHandler, Exception ex) throws Exception {
        if (mappedHandler != null) {
            mappedHandler.triggerAfterCompletion(request, response, ex);
        }

        throw ex;
    }
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 创作都市 设计师:CSDN官方博客 返回首页