springboot 提供了默认的 error 页面,路径为 ${server.error.path:${error.path:/error}},但是应用抛出异常的时候,可能会有部分重要的信息没有传递过去,导致 error 页面无法显示。
在 spring 中,提供了 @ControllerAdvice 注解和 @ExceptionHandler 注解,可以用于捕获全局异常。参考 30 个 Spring 常用注解与差异总结。
根据 springboot 代码,可以往 request 中添加 attribute 来传递信息给到 error 页面。其中:
最终,实现代码如下:
@ControllerAdvice public class Exception { @ExceptionHandler(MyException.class) public void handler(MyException e, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(ErrorCodeEnum.REQ_NOT_FOUND.name().equals(e.getErrorCode().getCode())){ request.setAttribute("javax.servlet.error.status_code", 404); request.setAttribute("javax.servlet.error.message", e.getErrorCode().getMsg()); request.setAttribute("javax.servlet.error.request_uri", request.getRequestURI()); } request.getRequestDispatcher("/error").forward(request, response); } }
本文来源:程序之心,转载请注明出处!
新文推荐
© 2016 - 2022 chengxuzhixin.com All Rights Reserved.