添加字段时,为了防止字段唯一,添加时重复。通过捕获异常将重复的字段抛出提示用户字段重复,请重新添加
代码效果:
/*
* @ControllerAdvice : 指定拦截那些类型的控制器;
* @ResponseBody: 将方法的返回值 R 对象转换为json格式的数据, 响应给页面;
* 定义一个全局异常处理器
* */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/*
* 异常处理方法
* */
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public String exceptionHandler(SQLIntegrityConstraintViolationException exception) {
log.error(exception.getMessage());
if (exception.getMessage().contains("Duplicate entry")) {
String[] split = exception.getMessage().split(" ");
log.info("获取到字符串的类容:{}", split);
// 获取字段中重复的信息
String msg = split[2] + "已存在";
// 根据自己的需求选择返回形式(这里为了方便,返回形式是String类型)
return msg;
}
return "未知错误"; // 根据自己的需求选择返回形式(这里为了方便,返回形式是String类型)
}
}
代码目的: