我在表中的列上添加了唯一约束。当违反约束时,它会引发一个我无法捕捉并传达给用户的异常。
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
根本不打印。也尝试了使用不同异常类的多个捕获。没有任何效果。
发送此类通用错误消息无济于事。