1.问题
当新建员工时,由于用户名uername是不可重复的,所以新建员工时我们使用了数据库中存在的username时,系统会出现异常,我们需要因此编写异常处理。
2.方法
方法一:我们可以使用try catch方法进行异常处理。
try{
employeeService.addMember(employee);
}catch(Exception e){
R.error("失败");
}
方法二:新建一个全局异常处理器。
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;
/*
* 全局异常处理
* */
//这里anntations利用注解指定处理的范围(使用RestController、controller注解的类里的所有函数都会进行异常处理)
@ControllerAdvice(annotations = {RestController.class, Controller.class})
//使用@ResponseBody将结果封装成JSON数据返回
@ResponseBody
//日志打印
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
log.error(exception.getMessage());
return R.error("失败了");
}
}