How do I prevent exceptions from causing a transaction rollback under Grails?

前端 未结 2 1782
渐次进展
渐次进展 2021-02-05 14:09

My Grails service is having an issue where a swallowed exception unrelated to a transaction is causing the transaction to rollback even when it is unrelated to the persistance o

相关标签:
2条回答
  • 2021-02-05 14:49

    You can use annotations to do more fine-grained transaction demarcation. By default services are transactional, and all public methods are transactional. But if you use any @Transactional annotations, Grails doesn't make everything transactional - you have complete control.

    Runtime exceptions automatically trigger rollbacks, but checked exceptions don't. Even though Groovy doesn't required that you catch checked exceptions, the feature is a Spring thing which doesn't know about Groovy exception handling.

    Transactions are implemented by wrapping your service class instance in a proxy. If an exception "escapes" the proxy, whether it's then caught or not, the rollback will have already happened.

    So you have a few options. Annotate updateSomething as @Transactional but don't annotate cleanUpOldFile:

    import org.springframework.transaction.annotation.Transactional
    
    @Transactional
    def updateSomething(domainObj) {
    ...
    }
    
    def cleanUpOldFile(...) {
       ...
    }
    

    You can also annotate cleanUpOldFile with one or more unchecked exceptions that shouldn't roll back a transaction (or in other use cases checked exceptions that should), e.g.

    @Transactional(noRollbackFor=[FooException, BarException])
    def cleanUpOldFile(...) {
       ...
    }
    
    0 讨论(0)
  • 2021-02-05 15:07

    In addition to @Burt Beckwith's answer, if you have a service where you just don't want transactions (which I actually did in my case) you can turn off transactions on all public methods by adding

    static transactional = false
    

    to the Service class.

    0 讨论(0)
提交回复
热议问题