统一处理异常(十六)

  • @ControllerAdvice
    • 用于修饰类,表示该类是Controller的全局配置类。
    • 在此类中,可以对Controller进行如下三种全局配置:异常处理方案、绑定数据方案、绑定参数方案。
  • @ExceptionHandler
    • 用于修饰方法,该方法会在Controller出现异常后被调用,用于处理捕获到的异常。
  • @ModelAttribute
    • 用于修饰方法,该方法会在Controller方法执行前被调用,用于为Model对象绑定参数。
  • @DataBinder
    • 用于修饰方法,该方法会在Controller方法执行前被调用,用于绑定参数的转换器。

一、异常页面跳转

将对应错误状态的页面,比如404.html,505.html,放到/resources/templates/error路径下,发生相应错误时SpringBoot会自动跳转(页面已经被thymeleaf处理)。

二、统一异常处理

1.声明错误页面的访问路径

便于后续统一处理完异常后重定向到错误页面。
HomeController.java

    @RequestMapping(path = "/error", method = RequestMethod.GET)
    public String getErrorPage() {
        return "/error/500";
    }

2.声明Conrtoller全局配置(通知)类

ExceptionAdvice.java

@ControllerAdvice(annotations = Controller.class) // annotations:扫描带有该注解的bean
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({Exception.class}) // 处理该类型的异常
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常: " + e.getMessage());
        for (StackTraceElement element : e.getStackTrace()) {
            logger.error(element.toString());
        }

        // 判断是请求的页面还是异步的json数据
        String xRequestedWith = request.getHeader("x-requested-with");
        if ("XMLHttpRequest".equals(xRequestedWith)) {
            // 异步请求,返回错误的json字符串
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(CommunityUtil.getJSONString(1, "服务器异常!"));
        } else {
            // 普通请求,重定向到错误页面
            response.sendRedirect(request.getContextPath() + "/error");
        }
    }

}
posted @   DaleLee  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示