knorv
knorv

Reputation: 50127

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?

Upvotes: 5

Views: 6262

Answers (2)

knorv
knorv

Reputation: 50127

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.

Upvotes: 9

codeLes
codeLes

Reputation: 3069

This isn't the cleanest looking, and there is probably a better, groovier way to do this. Based on looking here I put together this code that might be something you could expand and use:

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

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

def b = new Book()

b.customPrintTitle()

Upvotes: 0

Related Questions