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 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; } }