当我们新增员工时输入的账户已经存在,由于employee表中对该字段加入唯一约束,此时程序会抛出异常:
Duplicate entry '123456' for key 'employee.idx_username'
此时需要我们的程序进行异常捕获,通常的处理方式有两种:
1,在Controller方法中加入try,catch进行捕获
2,使用异常处理器进行全局异常捕获
下面是使用异常类进行全局捕获
package com.itheima.reggie.common;
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.RestController;
import java.sql.SQLIntegrityConstraintViolationException;
@ControllerAdvice(annotations = {RestController.class,Controller.class})
@RestController
@Slf4j
public class GlobalExceptionHandle {
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
log.error(ex.getMessage());
/* if (ex.getMessage().contains())*/
if (ex.getMessage().contains("Duplicate entry")){
String[] splite =ex.getMessage().split(" ");
String msg =splite[2] + "已存在";
return R.error(msg);
}
return R.error("未知错误");
}
}