定义一个全局的异常类
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> doException(SQLIntegrityConstraintViolationException e){
if (e.getMessage().contains("Duplicate entry")){
String[] s = e.getMessage().split(" ");
String errormsg ="用户["+ s[2]+"]已经存在";
return R.error(errormsg);
}
return R.error("未知错误");
}
}
1.@ControllerAdvice(annotations = {RestController.class, Controller.class})
检测拥有该注解的类
2.@ResponseBody
响应回数据
3.@ExceptionHander()
写入需要捕获的异常