Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

o.errors.allErrors.each { println it } by default when failing to save a domain object

When persisting domain objects using Grails/GORM I frequently find myself wondering why a save() call fails.

This can easily be solved by adding the logic:

if (!o.save()) {
    o.errors.allErrors.each { println it }
}

However, adding this everywhere I do a .save() adds a lot of duplicate code. In the spirit of DRY I'd like to configure Grails/GORM to automatically print any save-errors to the console (stderr). Is that possible? If not, how do I extend GORM to make it possible?

like image 414
knorv Avatar asked Mar 04 '09 16:03

knorv


1 Answers

Solution:

Object.metaClass.s = {
    def o = delegate.save()
    if (!o) {
        delegate.errors.allErrors.each {
            println it
        }
    }
    o
}

This adds a method called s() that will call save() and print any errors.

like image 168
knorv Avatar answered Oct 01 '22 09:10

knorv