user1069528
user1069528

Reputation: 618

Spring Hibernate eats exceptions

With @Transaction and with trace level logging of Spring I see that Hibernate has an exception on a db constraint but it just rolls back the transaction. I tried using @Exception without success to try to catch it.

I see a suggestion online to use Spring AOP @AfterThrowing to catch such events.

This seems like a rather complex way to handle a commonplace event. It seems so much easier with try/catch and old fashioned commits/rollbacks. Is there no better way in Spring Hibernate?

I'm processing XML messages from a queue. Depending on the type of the exception I get I might want to just catch it and put the bad incoming queue message into an db error table and continue the transaction. (If I just blindly rollback the message will get put back on the queue which might be good in some cases but not in others).

From what I've read there are ways of being made aware of some errors (for some reason not the constraint error) and logging them. Are there ways of interrupting the transaction after an exception and deciding if one wants to commit, continue or rollback?

If not, can one use old style commits and rollback with spring hibernate?

Upvotes: 0

Views: 373

Answers (1)

isah
isah

Reputation: 5341

Configure SimpleMappingException resolver and log the exception there:

public class MyExceptionResolver extends SimpleMappingExceptionResolver {
private Logger logger = LoggerFactory.getLogger(MyExceptionResolver .class);

@Override
protected void logException(Exception ex, HttpServletRequest request) {
    this.logger.warn(buildLogMessage(ex, request), ex);
}

<bean class="com.mypackage.MyExceptionResolver"/>

EDIT:

You can choose to do anything. The above class has nothing to do with rolling back. It's useful to intercept exceptions and do whatever you want with them. By default, Spring rolls back for any RuntimeException. If you want to configure rollback policy:

@Transactional(rollbackFor = { CustomException.class})

or

@Transactional(noRollBackFor= { CustomException.class})

Upvotes: 1

Related Questions