有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用JOOQ,如何将SQLException映射到业务异常?

我正在使用JOOQ,并希望将某些SQLException映射到业务异常。文件页上写着:

The following section about execute listeners documents means of overriding jOOQ's exception handling, if you wish to deal separately with some types of constraint violations, or if you raise business errors from your database, etc.

然而,关于the page about execute listeners没有实际的例子

我知道我必须实现ExecuteListener的方法exception(ExecuteContext),但是我不清楚是否应该从那里throw另一个异常,或者使用ExecuteContext.exception方法来覆盖现有的异常。例如

@Override
public void exception(ExecuteContext ctx) {
    if (ctx.sqlException().getSQLState().equals("23503")) {
        throw new ForeignKeyViolationException("Foreign key violation", ctx.sqlException());
    }
}

或:

@Override
public void exception(ExecuteContext ctx) {
    if (ctx.sqlException().getSQLState().equals("23503")) {
        ctx.exception(ForeignKeyViolationException("Foreign key violation", ctx.sqlException()));
    }
}

共 (1) 个答案

  1. # 1 楼答案

    恐怕你得自己做这项工作。这就是为什么

    使用ExecuteListener对您无效

    如果您想要jOOQ的^{}的替代异常,例如Spring的^{}用于进一步处理(example translator here),那么选择ExecuteListener进行自动和全局翻译的方法非常有用。它不适合自动将约束冲突异常重新连接到特定的“业务异常”,因为ExecuteListener(作为全局参与者)不知道约束冲突可能发生在什么上下文中。可能有:

    • 导致违反约束的错误(例如,您应该更新,而不是插入)
    • 导致违反约束的用户错误(例如,用户提交了两次表单)
    • 导致违反约束的实际业务规则(例如检查约束)

    恐怕你必须为每一个查询单独决定这一点ExecuteListener只帮助您重新连接异常处理的技术部分

    为什么手册中提到“业务错误”

    您引用了手册:

    or if you raise business errors from your database

    这些业务错误可能是您从数据库触发器引发的用户定义错误,例如,在这种情况下,您不会得到约束冲突,而是直接从数据库中得到有意义的业务错误