由于用Controller写try和catch来捕获异常的方法可能要重复写很多次,代码很冗余,故采用全局异常捕获的方法:
新建一个GlobalExceptionHandler的捕获异常的类:
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})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/**
* 异常处理方法
* @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("未知错误");
}
}
其中,@Slf4j是日志打印注解,@ControllerAdvice(annotations = {RestController.class, Controller.class}指的是标注有RestController和Controller的类都在该异常捕获的范围内;
SQLIntegrityConstraintViolationException是数据库的异常类,if判断当error message包含"Duplicate entry"时,表明是由于不可重复属性重复导致的错误,比如两个人都叫zhangsan,单但先前在数据库中设定username为不可重复属性,此时便会报错。返回错误信息R.error。R是自己定义的结果类,包含success和error方法。