From 2116b5b5802c0de0f126f85cf2ac56a732639e82 Mon Sep 17 00:00:00 2001 From: xin <1099200748@qq.com> Date: Wed, 02 Jul 2025 16:39:16 +0800 Subject: [PATCH] Merge remote-tracking branch 'origin/master' into xin --- oying-common/src/main/java/com/oying/utils/DuplicateKeyExceptionUtil.java | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 files changed, 51 insertions(+), 0 deletions(-) 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