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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With