update 在全局异常处理器中引入DuplicateKeyException的主键冲突异常,来处理解决主键或UNIQUE索引的数据重复异常。

This commit is contained in:
xlt 2022-03-27 21:57:44 +08:00
parent a6f30412ad
commit 53c90cfc99

View File

@ -11,6 +11,7 @@ import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException; import org.springframework.validation.BindException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
@ -71,6 +72,16 @@ public class GlobalExceptionHandler {
return R.fail(e.getMessage()); return R.fail(e.getMessage());
} }
/**
* 主键或UNIQUE索引数据重复异常
*/
@ExceptionHandler(DuplicateKeyException.class)
public R<Void> handleDuplicateKeyException(DuplicateKeyException e, HttpServletRequest request) {
String requestURI = request.getRequestURI();
log.error("请求地址'{}',数据库中已存在记录'{}'", requestURI, e.getMessage());
return R.fail(HttpStatus.HTTP_INTERNAL_ERROR, "数据库中已存在该记录,请联系管理员确认");
}
/** /**
* 业务异常 * 业务异常
*/ */