Could please anybody tell me If it is safe and recommended to catch SQL and other exceptions within @Transactional methods ? When programmatic transaction management is used, I can simply catch the exception and do whatever I want, but I don’t know if I don’t break the transactional AOP system by catching these exceptions that would otherwise trigger the rollback … if I do it declarative way.
I suppose there are proxies, that create a logical transaction with separate connection for @Transactional methods in the AOP advices. And they need to catch the exception that “I want to catch” and roll the transaction back.
You can mark the transaction programmatically as rollback-only using this code
See Rolling back a declarative transaction in the Spring Reference.
But it’s not recommended, because you are coupling your code tightly to the spring framework.
Perhaps, if you do that in more than one place, you should introduce a Helper Method, something like
TransactionUtils.rollbackCurrentTransaction(). That way, if you decide to change your transactional approach (or god forbid, move away from spring), you only have to change one method.