oying-common/src/main/java/com/oying/exception/handler/GlobalExceptionHandler.java | ●●●●● patch | view | raw | blame | history | |
oying-common/src/main/java/com/oying/utils/DuplicateKeyExceptionUtil.java | ●●●●● patch | view | raw | blame | history |
oying-common/src/main/java/com/oying/exception/handler/GlobalExceptionHandler.java
@@ -1,10 +1,12 @@ package com.oying.exception.handler; import com.oying.exception.BadRequestException; import com.oying.exception.EntityExistException; import com.oying.exception.EntityNotFoundException; import lombok.extern.slf4j.Slf4j; import com.oying.exception.BadRequestException; import com.oying.utils.DuplicateKeyExceptionUtil; import com.oying.utils.ThrowableUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DuplicateKeyException; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.validation.FieldError; @@ -89,6 +91,16 @@ } /** * 处理 DuplicateKeyException */ @ExceptionHandler(value = DuplicateKeyException.class) public ResponseEntity<ApiError> handleDuplicateKeyException(DuplicateKeyException e) { // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); return buildResponseEntity(ApiError.error(BAD_REQUEST.value(), DuplicateKeyExceptionUtil.getDisplayMessage(e))); } /** * 统一返回 */ private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) { oying-common/src/main/java/com/oying/utils/DuplicateKeyExceptionUtil.java
New file @@ -0,0 +1,51 @@ package com.oying.utils; import cn.hutool.core.map.MapUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.dao.DuplicateKeyException; import java.sql.SQLException; import java.util.Map; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; @Slf4j public class DuplicateKeyExceptionUtil { public static final Map<String, String> INDEX_MAPPING = MapUtil.ofEntries( MapUtil.entry("pc_store.uk_store_name", "店铺名称") ); /** * 获取错误消息 */ public static String getDisplayMessage(DuplicateKeyException e) { try { String indexName = findMySQLDuplicateKey(e); String fieldDisplayName = INDEX_MAPPING.getOrDefault(indexName, indexName); return Optional.ofNullable(fieldDisplayName).map(o -> o + "已存在").orElse(e.getMessage()); } catch (Exception ex) { log.error("解析'DuplicateKeyException'消息失败", ex); return e.getMessage(); } } /** * 提取索引名称 */ public static String findMySQLDuplicateKey(DuplicateKeyException e) { if (e.getCause() instanceof SQLException) { SQLException sqlEx = (SQLException) e.getCause(); if (sqlEx.getErrorCode() == 1062) { // MySQL duplicate key error code String errorMsg = sqlEx.getMessage(); // 使用正则提取索引名 Matcher matcher = Pattern.compile("for key '(.+?)'").matcher(errorMsg); if (matcher.find()) { return matcher.group(1); } } } return null; } }