TBAR
TBAR

Reputation: 448

Grails, save domain class after exception has been thrown

Using grails 3.3.8

Any domainclass.save(flush:true,failOnError:true) does not get saved if a caught exception has been thrown in the service method where the save is being issued. i.e.

try {
    //some code that throws exception
} catch (Exception exception) {
    print 'some message'
}

domainclass.save(flush:true,failOnError:true)

Upvotes: 7

Views: 775

Answers (2)

Armando Prieto
Armando Prieto

Reputation: 129

Well, prior to Grails 3.1 services were transactional by default, as of Grails 3.1 they are only transactional if the @Transactional annotation is applied.

If you are on a transactional service when an exception is triggered the transaction will be marked to do rollback. At the same time when a transaction is rolled back the Hibernate session used by GORM is cleared.

I am assuming your service is being marked with @Transactional. That is why your domain is not being saved. To get around the behavior above described you could mark your service as @NotTransactional. That will provide you with more control over your service method, just be aware it won't be transactional anymore. And the GORM session will not be cleared after the exception is thrown.

EDIT: Because you're calling .save(), it is highly recommended to do it inside a transaction. You could then use the withTransaction(Closure) method.

Upvotes: -1

TBAR
TBAR

Reputation: 448

I found a work around to the above. If you extract your try catch block and put it in a different method the domain class save does get persisted.

i.e.

callMethodThatContainsTryCatch()
domainClass.save()

instead of

try {
} catch (Exception exception) {
    println "some exception"
}

domainClass.save()

It would then appear that any exception in your method rolls back of all gorm transactions within that method.

Upvotes: 2

Related Questions