DuplicateKeyExceptionHandler.java 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.backendsys.exception;
  2. import com.backendsys.utils.response.Result;
  3. import com.backendsys.utils.response.ResultEnum;
  4. import org.springframework.dao.DuplicateKeyException;
  5. import org.springframework.web.bind.annotation.RestControllerAdvice;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8. @RestControllerAdvice
  9. public class DuplicateKeyExceptionHandler {
  10. public Result handleDuplicateKeyException(DuplicateKeyException e) {
  11. System.out.println("****** DuplicateKeyException.class: ******");
  12. System.out.println(e);
  13. String errorMessage = e.getMessage();
  14. // Error selecting key or setting result to parameter object.
  15. // Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'a1' for key 'sys_user.username'\n;
  16. // Duplicate entry 'a1' for key 'sys_user.username'
  17. // [fieldName] 使用正则表达式提取 字段名
  18. Pattern pattern = Pattern.compile("for key '(.*?)'");
  19. Matcher matcher = pattern.matcher(errorMessage);
  20. String fieldName = matcher.find() ? matcher.group(1) : null;
  21. //// [yml] 读取配置文件中的字段名和友好提示的对应关系
  22. //Yaml yaml = new Yaml();
  23. //Map<String, Object> KLingAiConfig = null;
  24. //try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("application.yml")) {
  25. // KLingAiConfig = yaml.load(inputStream);
  26. //} catch (IOException ex) {
  27. // // 处理配置文件读取错误
  28. // ex.printStackTrace();
  29. //}
  30. //// [friendlyMessage] 获得自定义友好提示 (application.yml -> fieldMappings)
  31. //String friendlyMessage = null;
  32. //if (KLingAiConfig != null && KLingAiConfig.containsKey("fieldMappings")) {
  33. // Map<String, Object> fieldMappings = (Map<String, Object>) KLingAiConfig.get("fieldMappings");
  34. // for (Map.Entry<String, Object> entry : fieldMappings.entrySet()) {
  35. // String fieldKey = entry.getKey();
  36. // if (errorMessage.contains(fieldKey)) {
  37. // friendlyMessage = (String) entry.getValue();
  38. // break;
  39. // }
  40. // }
  41. //}
  42. // [fieldValue] 获得字段的入参
  43. String fieldValue = null;
  44. String patternFieldValue = "Duplicate entry '(.+)' for key '";
  45. Pattern regex = Pattern.compile(patternFieldValue);
  46. Matcher matcherFieldValue = regex.matcher(errorMessage);
  47. if (matcherFieldValue.find()) {
  48. fieldValue = matcherFieldValue.group(1).trim();
  49. }
  50. //return Result.error(ResultEnum.UNIQUE_FIELD.getCode(), friendlyMessage , fieldName + ": " + fieldValue);
  51. return Result.error(ResultEnum.UNIQUE_FIELD.getCode(), fieldValue + " 已存在" , fieldName + ": " + fieldValue);
  52. }
  53. }