Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid org.springframework.transaction.UnexpectedRollbackException?

When a method is annotated with @Transactional and there is an runtime exception, spring eats the exception and throws:

org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only

How do I avoid this "general" exception and propagate the original exception, but keeping the rollback?

Thanks.

like image 392
Thiago Sayão Avatar asked May 28 '19 16:05

Thiago Sayão


1 Answers

org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only

It mostly happens if you have an outer @Transactional method calls an inner @Transactional method. When the inner method throws an exception , but the outer method catches this exception and return normally, Spring is confused and don't know if it should rollback or commit the transaction since both methods contradict with each other. (Inner method says it wants to rollback but the outer method says it want to commit)

So , check if there are any outer @Transactional methods that catch the exception. If yes , re-throw that exception from the outer method such that the whole transaction will rollback.

like image 63
Ken Chan Avatar answered Sep 23 '22 23:09

Ken Chan