Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Grails notify me of error at domain object saving?

I'm just starting with Grails, and here is the first issue.

I spent several hours to find out that domain object cannot be inserted in DB, until all its properties are populated.

class Item {
  String title
  String link
}

class ItemController {
  def fetch = {
    def item = new Item()
    item.title = "blabla"
    // no value for "link"
    item.save()
  }
}

Looks logical, but why is it skipped so silently? Can I configure something to get exceptions in such cases?

Thanks

like image 435
mkuzmin Avatar asked Jan 21 '11 23:01

mkuzmin


2 Answers

No exception is thrown by default .

The save() method injected to Domain classes returns false if an error has occured during the validation phase. A classic code sample for checking save/update of a domain class is :

if (!myDomainObj.save()) {
   log.warn myDomainObj.errors.allErrors.join(' \n') //each error is an instance of  org.springframework.validation.FieldError    
}

If you need to have an exception for a particular domain class, use:

myDomainObj.save(failOnError: true)

and exceptions for validation failures will be thrown.

If you want to throw an exception for EVERY domain classes, then simply set grails.gorm.failOnError to true in grails-app/conf/Config.groovy

Be carefull : all domain properties have an implicit nullable: false constraint.

I recommend you reading this article.

like image 135
fabien7474 Avatar answered Nov 25 '22 21:11

fabien7474


To make your save() call throw a RuntimeException, you can use item.save(failOnError:true) . But you can also check the return value of save() method. If it's false, that means something wrong happened.

if (item.save()) {
   //succeeded
}
else  {
   //not succeeded
}
like image 30
yogiebiz Avatar answered Nov 25 '22 21:11

yogiebiz