Grails gorm捕获外键约束错误

时间:2014-05-22 05:48:33

标签: grails gorm

在Grails中,我希望在出现外键约束时捕获异常,这是我的代码

    try {
        instance.delete(flush:true)
        flash.message = message(code : "default.deleted.message", args : [instance])
        flash.level = "info"
    } catch(org.springframework.dao.DataIntegrityViolationException | Exception e) {
        flash.message =  message(code : "default.not.deleted.message", args :  [instance])
        flash.level = "danger"
    }

问题是当存在外键约束时,它永远不会进入catch块。 知道我应该添加什么异常吗?

谢谢,

2 个答案:

答案 0 :(得分:1)

我认为这是因为updateinsert投放了MySQLIntegrityConstraintViolationException而不是delete

Exception thrown when an attempt to insert or update data results in violation of an
 integrity constraint. Note that this is not purely a relational concept; unique primary
 keys are required by most database types.

尝试使用com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException

修改

您使用的是哪种版本的 Grails

我发现了这个问题GRAILS-9357

答案 1 :(得分:1)

我正在使用grails 2.3.5,以下代码适用于我

try {
    user.delete(flush: true)
    render "OK"
} catch (org.springframework.dao.DataIntegrityViolationException e) {
    render "DataIntegrityViolationException"
} catch (Throwable v) {
    render "Throwable"
}

试试这个..,。