简体   繁体   中英

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

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 .

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM