• AOP全局异常处理


    AOP全局异常处理

    由于Controller可能接收到来自业务层、数据层、数据库抛出的异常,因此需要使用AOP思想,进行全局异常处理,异常可通过调试获得。

    package org.sinian.reggie.common;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.sql.SQLIntegrityConstraintViolationException;
    
    @ControllerAdvice(annotations = {RestController.class, Controller.class})//表示这是一个aop通知类,做功能增强。
    @ResponseBody//类中方法返回值将以JSON格式返回给前端。
    @Slf4j//日志记录
    public class GlobalExceptionHandler {
     
        @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//表明该方法为一个异常处理器。
        public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
            log.error(ex.getMessage());
    
            if(ex.getMessage().contains("Duplicate entry")){
                String[] split = ex.getMessage().split(" ");
                String msg = split[2] + "已存在";
                return R.error(msg);
            }
    
            return R.error("未知错误");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • (SQLIntegrityConstraintViolationException:

      • 唯一性约束违反:尝试插入已经存在的唯一值(例如,违反了唯一索引)。
      • 主键约束违反:尝试插入重复的主键值。
      • 外键约束违反:尝试插入或更新关联表的外键值,但没有匹配的主键值。
      • 检查约束违反:尝试插入或更新值,不满足定义的检查条件。
    • 总结:通过两个注解实现全局异常处理

      • @ControllerAdvice(annotations = {RestController.class, Controller.class})
      • @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
  • 相关阅读:
    一文讲清楚网络安全是什么?网络安全工程师需要学什么?就业前景如何?
    Vue-04-axios异步通信
    LQ0274 密码发生器【水题】
    导入导出Excel
    【函数指针】
    流体的压力
    Qt浏览器模块的几点说明
    新手开抖店——一定忽略的“发货”问题,违规必扣保证金!
    intellij idea的快速配置详细使用
    用Jmeter测试的数据
  • 原文地址:https://blog.csdn.net/sinian_sinian/article/details/132891563