Home > Mobile >  try/catch with @Transactional throws TransactionException instead of catch's exception
try/catch with @Transactional throws TransactionException instead of catch's exception

Time:12-31

I have a problem, my controller is marked as @Transactional and I have a method, that has try/catch block that is supposed to catch DataIntegrityViolationException, and everything is fine, the catch is executed, but in the end I do not see the message from catch, but I can see this:

Caused by Transaction was marked for rollback only; cannot commit
Caused by TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction was marked for rollback only; cannot commit

Adding @Transactional(noRollbackFor = DataIntegrityViolationException.class) doesn't solve the problem, I still get the TransactionException instead of DataIntegrityViolationException exception,

The method is like this:

def delete() {
 try {
   something.delete();
 } catch (DataIntegrityViolationException e) {
   flash.message = "some error"
 }

CodePudding user response:

First of all, you shouldn't make a transactional controller.

Second, DataIntegrityViolationException is thrown from something.delete();, but TransactionException is thrown when you return from the method marked with @Transactional - Spring's transaction manager tries to commit the transaction, which has already been marked for rollback because of DataIntegrityViolationException. What you should do is to move @Transactional into the service layer and wrap the call to it with try-catch within controller's method.

  • Related