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 - 2024 chengxuzhixin.com All Rights Reserved.