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})//annotations注解的意思拦截添加了RestController
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
// 添加@ExceptionHandler注解,参数为要处理的哪个异常类,方法名任意
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
log.error(ex.getMessage());
// 异常信息中包含"Duplicate entry"这个关键字说明字段重复
if(ex.getMessage().contains("Duplicate entry")){
String[] split = ex.getMessage().split(" ");
String name = split[2]+"已存在";
return R.error("msg");
}
return R.error("未知错误");
}
}
年少轻狂,总以为天下事竭力有为。人事尽时,终感力不能及。