MySQL 主键冲突异常如何全部捕获?

转自:https://blog.csdn.net/wenniuwuren/article/details/88887813

很多时候只要觉得捕获 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) 始终没有出现。不知道是否真的像原博主那样会出现此异常。

参考文章:
1、https://blog.csdn.net/wenniuwuren/article/details/88887813