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("未知错误");
}
}
-
(SQLIntegrityConstraintViolationException:
- 唯一性约束违反:尝试插入已经存在的唯一值(例如,违反了唯一索引)。
- 主键约束违反:尝试插入重复的主键值。
- 外键约束违反:尝试插入或更新关联表的外键值,但没有匹配的主键值。
- 检查约束违反:尝试插入或更新值,不满足定义的检查条件。
-
总结:通过两个注解实现全局异常处理
- @ControllerAdvice(annotations = {RestController.class, Controller.class})
- @ExceptionHandler(SQLIntegrityConstraintViolationException.class)