spring-jdbc 异常抽象

根据spring-jdbc 中的定义 所有的数据操作异常都会转换为 DataAccessException

由于不同的数据库平台 存在不同的错误码定义,默认使用org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator进行转换

对于相关错误码定义 可以参考 spring-jdbc 中  org/springframework/jdbc/support/sql-error-codes.xml 中相关错误码定义, 可以看到其对于不同的平台设置了不同的定义

 

对于自定义异常相关配置,一般按照以下步骤

  1. 自定义异常类
  2. 参考spring-jdbc中的sql-error-codes.xml 创建新的 ql-error-codes.xml 文件 存放到当前项目 classpath 目录下
    1. 设置 指定bean 中 org.springframework.jdbc.support.SQLErrorCodes#customTranslations 属性
    2. 设置 org.springframework.jdbc.support.CustomSQLErrorCodesTranslation#errorCodes 错误码定义
    3. 设置 org.springframework.jdbc.support.CustomSQLErrorCodesTranslation#exceptionClass 指定错误码对应的异常信息

对于 sql异常错误码转换器 org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator#doTranslate 会优先匹配自定义的错误码(org.springframework.jdbc.support.SQLErrorCodes#customTranslations)

关于 classpaths:sql-error-codes.xml(自定义)代码如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "https://www.springframework.org/dtd/spring-beans-2.0.dtd">

<!--
    - 自定义异常错误码
    -->
<beans>
    <!--设置 H2 数据库相关异常-->
    <bean id="H2" class="org.springframework.jdbc.support.SQLErrorCodes">
        <property name="badSqlGrammarCodes">
            <value>42000,42001,42101,42102,42111,42112,42121,42122,42132</value>
        </property>
        <property name="duplicateKeyCodes">
            <value>23001,23505</value>
        </property>
        <property name="dataIntegrityViolationCodes">
            <value>22001,22003,22012,22018,22025,23000,23002,23003,23502,23503,23506,23507,23513</value>
        </property>
        <property name="dataAccessResourceFailureCodes">
            <value>90046,90100,90117,90121,90126</value>
        </property>
        <property name="cannotAcquireLockCodes">
            <value>50200</value>
        </property>
     <!--重点如下--> <!--设置自定义异常转换器--> <!--// Look for defined custom translations first--> <!--当设置自定义异常时,会优先匹配自定义异常--> <property name="customTranslations"> <!--设置当前自定义sql异常定义转换器--> <bean class="org.springframework.jdbc.support.CustomSQLErrorCodesTranslation"> <!--设置拦截的自定义错误码--> <property name="errorCodes"> <value>23001,23505</value> </property> <!--设置拦截到错误码后抛出的异常类型--> <property name="exceptionClass"> <value>com.xingguo.spring.jdbc.exception.CustomDuplicateKeyException</value> </property> </bean> </property> </bean> </beans>

 

 github 相关源码:https://github.com/mengyan183/spring-family/tree/main/spring-jdbc-exception   

 

posted @ 2020-12-22 16:06  郭星  阅读(527)  评论(0)    收藏  举报