MySQL 主键冲突异常如何全部捕获?
很多时候只要觉得捕获 DuplicateKeyException 就行,其实这样还不够,底层还会抛出其他异常类型,完整的捕获如下:
import org.springframework.dao.DuplicateKeyException; public void method() { try { result = dao.insert(shopkeeperIndexDO); } catch (DuplicateKeyException e) { // do something } catch (Exception e) { String errorCode = getErrorCode(e); // 这也是主键冲突异常 if (errorCode.indexOf("Duplicate entry") >= 0) { // do something } // do something } } private String getErrorCode(Exception e) { String errorCode = ""; if (e.getCause() != null && e.getCause().getMessage() != null) { errorCode = e.getCause().getMessage(); } if (Strings.isNullOrEmpty(errorCode) && e.getMessage() != null) { errorCode = e.getMessage(); } return errorCode; }
使用的mybatis框架。自测过程中 catch (Exception e) 始终没有出现。不知道是否真的像原博主那样会出现此异常。
转载:https://blog.csdn.net/yangyangrenren/article/details/118074041
带着疑问去思考,然后串联,进而归纳总结,不断追问自己,进行自我辩证,像侦查嫌疑案件一样看待技术问题,漆黑的街道,你我一起寻找线索,你就是技术界大侦探福尔摩斯

浙公网安备 33010602011771号