Grails Tip: Using failOnError When Saving Domain Instances

Calling the save method on a Grails domain class will return a null if there was an error in validation. This is handy when doing something like the following.

if ( !book.save() ) {
   book.errors.each {
        printlnit
   }
}

In Grails 1.2 a feature was added to allow the option of forcing save to throw a grails.validation.ValidationException by using the failOnError argument.

try {
   book.save(failOnError:true)
} catch(ValidationException e) {
   // handle
}

If you prefer to make failing on validation errors the default, you can update Config.groovy in your Grails project to set the following property.

grails.gorm.failOnError=true

Thanks to Jeff Brown for reminding me of this when replying to a recent thread on the Grails user email list.