zepengdev
2025-06-26 97a55d2e9a7e6ee36d95e08731dd374f5fd93fa1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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;
    }
}