使用 spring-data-r2dbc 和 postgresql 从 DataIntegrityViolationException 获取失败约束名称

fpa*_*fpa 5 spring-data-r2dbc r2dbc r2dbc-postgresql

我在 postgresql 数据库中有一些限制(唯一的、外键...)。

我使用 spring data r2dbc 存储库:ReactiveCrudRepository

我想将DataIntegrityViolationException存储库的抛出转换为基于 的constraintNameinErrorDetails字段的自定义异常PostgresqlDataIntegrityViolationException

ExceptionFactory包含该类的类PostgresqlDataIntegrityViolationException是包私有的。所以我无法投射DataIntegrityViolationExceptionto的原因异常PostgresqlDataIntegrityViolationException

constraintName当我捕获 时,访问 的最干净的方法是什么DataIntegrityViolationException

(比解析异常消息更好的事情^^)

编辑 :

我以这个解决方案结束:

    val DataIntegrityViolationException.pgErrorDetails: ErrorDetails
        get() = when(val cause = this.cause) {
                null -> error("cause should not be null")
                else -> cause.javaClass
                        .getDeclaredField("errorDetails")
                        .apply { isAccessible = true }
                        .let { it.get(cause) as ErrorDetails }
                }
Run Code Online (Sandbox Code Playgroud)

Ign*_*lla 1

 Myr2dbcRepo.save(myEntity).doOnError(cause -> {
     PostgresqlException pe =(PostgresqlException) cause.getCause();
     ErrorDetails ed = pe.getErrorDetails();
 }).suscribe();
Run Code Online (Sandbox Code Playgroud)

请考虑到 DataIntegrityViolationException 只是您正在使用的 dbDriver 异常的 Spring Boot 包装器,在本例中为 R2DBC。

此外,您可能需要将 R2DBC-POSTGRES 依赖项的范围从“运行时”更改为“实现”。

最后请注意,我的代码示例是在 java 上的,我确信您不会费力将其翻译为 kotlin。