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

 

 

 

 

 

posted @   迷走神经  阅读(768)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示