- 员工表给账号字段增加了唯一索引,添加同名账号报错:
java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'admin' for key 'idx_username'
- 添加全局异常处理器,在里面处理具体报错
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 表示这是一个关于Controller的通知,拦截类上加了注解RestController,Controller的类
* @ResponseBody 将结果封装成json格式返回
* @Slf4j 方便打印日志
*/
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/**
* 异常处理方法
* @ExceptionHandler
* SQLIntegrityConstraintViolationException.class 要处理的异常类
* Controller抛的SQLIntegrityConstraintViolationException异常都会在这里处理
* @return
*/
@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("未知错误");
}
}
- 效果