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

前端 未结 2 1783
渐次进展
渐次进展 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(...) {
       ...
    }
    

提交回复
热议问题