Video in progress
Why does this code produce the error "Transaction silently rolled back because it has been marked as rollback-only"?
@Service
class OrderService {
private final BonusService bonusService;
@Transactional
public void placeOrder(Order o) {
orderRepository.save(o);
try {
bonusService.addBonus(o.customerId()); // @Transactional, throws RuntimeException
} catch (RuntimeException e) {
log.warn("Bonus qo'shilmadi", e);
}
}
}
When the inner @Transactional method throws an exception, it is the same transaction as the outer one (REQUIRED), so the whole transaction is marked rollback-only. If the outer method swallows the exception and finishes normally, the commit attempt throws UnexpectedRollbackException.
📖 Answer
bonusService.addBonus is in another bean, so it's called through a proxy. Since it's also REQUIRED, it doesn't open a new transaction but joins the outer one. As the exception leaves the proxy, TransactionInterceptor sees it and marks the shared transaction as rollbackOnly. You did catch it, but the mark stays.
placeOrder finishes normally, the outer proxy tries to commit, sees the mark, rolls back and throws UnexpectedRollbackException about it. The result: the order wasn't saved either, and on top of that the caller got a confusing error.
Ways to fix it, depending on the goal:
| Goal | Solution |
|---|---|
| The order should be saved even if the bonus fails | make addBonus @Transactional(propagation = REQUIRES_NEW) |
| This exception is an expected business case | @Transactional(noRollbackFor = BonusLimitException.class) |
| The bonus should be entirely outside the transaction | do it through an event after the order commits |
The worst solution is to keep "swallowing" the exception in the outer method and ignore the error in the log. When you see this error, the first question is: "which inner call throws an exception that is then caught?".
Sign up to mark studied questions and save your progress.