O.errors.allErrors.each {println it} by default if it is not possible to save the domain object

When saving domain objects using Grails / GORM, I often wonder why the save () call fails.

This is easy to solve by adding logic:

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

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

+5
source share
2 answers

Decision:

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

This adds the s () method, which will call save () and print any errors.

+9
source

, , , , . , -, :

class Book {
   void printTitle(){ println "The Title" }
}

Book.metaClass.customPrintTitle << {-> 
    println "changin ur class"
    printTitle()
}

def b = new Book()

b.customPrintTitle()
0

All Articles