2
votes

In Grails i want to catch the exception when foreign key constraint appears, this is my code

    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"
    }

The problem is when there is a foreign key constraint, it never enters the catch block. Any idea what exception i should add ?

Thanks,

2

2 Answers

2
votes

I am using grails 2.3.5 and following code works for me

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

Try this..,.

1
votes

I think it is because MySQLIntegrityConstraintViolationException is thrown on update or insert not 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.

Try with com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException

EDIT

Which version of Grails are you using ?

I found this issue GRAILS-9357