grailsgrails-ormunique-constraintgrails-domain-classgrails-validation

Grails Error Code


I am trying to determine what the Error Code is from an exception that is thrown when interacting with a domain object in Grails.

I have a database that has some field validations, and one of the validations is that a specific column must be unique. According to the docs it will give an Error Code of className.propertyName.unique(http://grails.org/doc/latest/ref/Constraints/unique.html). When I wrap my controller in a try catch block like. I can catch all kinds of validation exceptions this:

catch (grails.validation.ValidationException e) {  
    exception handling code here  
}    

How do I access the Error Code? I would like to do something like If the Error Code = className1.propertyName2.unique, then respond propertyName2 is not unique.

I do have "failOnError: true" set as a parameter when I do my save operation.

Thanks!


Solution

  • The Error Code is burried deep within the object. It will be one of the items in the list that is returned by calling the following code, where 'e' is the exception object.

    e.getErrors().getFieldError()
    

    You can also get just the code ("unique" in this case) from the exception by calling the following:

    e.getErrors().getFieldError().getCode()