From 97a55d2e9a7e6ee36d95e08731dd374f5fd93fa1 Mon Sep 17 00:00:00 2001
From: zepengdev <lzpsmith@outlook.com>
Date: Thu, 26 Jun 2025 22:24:30 +0800
Subject: [PATCH] fix: 优化DuplicateKeyException异常消息展示

---
 oying-common/src/main/java/com/oying/exception/handler/GlobalExceptionHandler.java |   16 +++++++-
 oying-common/src/main/java/com/oying/utils/DuplicateKeyExceptionUtil.java          |   51 +++++++++++++++++++++++++
 2 files changed, 65 insertions(+), 2 deletions(-)

diff --git a/oying-common/src/main/java/com/oying/exception/handler/GlobalExceptionHandler.java b/oying-common/src/main/java/com/oying/exception/handler/GlobalExceptionHandler.java
index 1c92ae1..f33a0bb 100644
--- a/oying-common/src/main/java/com/oying/exception/handler/GlobalExceptionHandler.java
+++ b/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) {
diff --git a/oying-common/src/main/java/com/oying/utils/DuplicateKeyExceptionUtil.java b/oying-common/src/main/java/com/oying/utils/DuplicateKeyExceptionUtil.java
new file mode 100644
index 0000000..6132e97
--- /dev/null
+++ b/oying-common/src/main/java/com/oying/utils/DuplicateKeyExceptionUtil.java
@@ -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;
+    }
+}

--
Gitblit v1.9.3