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 ++++++++++++++--
 1 files changed, 14 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) {

--
Gitblit v1.9.3