1

我在表中的列上添加了唯一约束。当违反约束时,它会引发一个我无法捕捉并传达给用户的异常。

Exposed: Transaction attempt #0 failed: java.sql.BatchUpdateException: Batch entry 0 INSERT INTO templates (created_at, is_deleted, name, sections) VALUES ('2018-10-03 16:31:25.732+05:30', 'FALSE', 'Template1', '[{"title":"Introduction"}]') RETURNING * was aborted: ERROR: duplicate key value violates unique constraint "templates_name_key" Detail: Key (name)=(Template1) already exists. Call getNextException to see other errors in the batch.. Statement(s): INSERT INTO templates (created_at, is_deleted, name, sections) VALUES (?, ?, ?, ?) ! org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "templates_name_key" ! Detail: Key (name)=(Template1) already exists.

  • 如何使用用户可读的消息捕获这些类型的 SQL 异常?
  • 是否有任何最佳实践来捕获这些异常?
  • 我们应该在事务内部还是外部捕获它们?有没有这样的必要性?

下面是我试过的片段。

return try {
    val template: TemplateSerializer = transaction {
        val newTemplate = Template.insert(request)
        TemplateSerializer.serialize(newTemplate)
    }
    Response.status(201).entity(template).build()
} catch (e: Exception) {
    if(e is SQLIntegrityConstraintViolationException) {
        resourceLogger.error("SQL constraint violated")
    } else if(e is BatchUpdateException) {
        resourceLogger.error("SQL constraint violated")
    } else
        resourceLogger.error(e.message)
    Response.status(422).entity(mapOf("error" to true, "message" to "Insertion failed")).build()
}

消息SQL constraint violated根本不打印。也尝试了使用不同异常类的多个捕获。没有任何效果。

发送此类通用错误消息无济于事。

4

2 回答 2

2

暴露的 throwsExposedSQLException是一个子类型,SQLException可以通过函数访问最新执行的查询(可能导致原始异常)causeByQueries()。原始异常可通过cause属性访问。

return try {
    val template: TemplateSerializer = transaction {
        val newTemplate = Template.insert(request)
        TemplateSerializer.serialize(newTemplate)
    }
    Response.status(201).entity(template).build()
} catch (e: Exception) {
    val original = (e as? ExposedSQLException)?.cause
    when (original) {
      is SQLIntegrityConstraintViolationException -> 
        resourceLogger.error("SQL constraint violated")
      is BatchUpdateException -> 
        resourceLogger.error("SQL constraint violated")
      else ->
        resourceLogger.error(e.message)
    }
Response.status(422).entity(mapOf("error" to true, "message" to "Insertion failed")).build()
于 2018-10-04T06:49:19.057 回答
1

您可以检查sqlState.

它看起来像:

try {
        userService.insertUser(user)
    } catch (e: ExposedSQLException) {

        val isUniqueConstraintError = e.sqlState == "23505"
    }

您可以从那里获取正确的错误代码:

https://www.postgresql.org/docs/10/errcodes-appendix.html

于 2020-10-08T13:43:15.000 回答