Question

I have a problem running some code right before a transaction rollback in my application. What I want is to have a rollback when an exception occurs but I also want to store some information in a table about the application's state when that exception happened including any errors or stacktrace.

Here is the code I have:

public void performAction(String approverId, Document document, String action) {
        try {
            LOG.info(String.format("routing document %s %s %s", approverId, document.getDocumentId(), action));
            getDocumentService().route(approverId, document, action);
        } catch (Exception e) {
            LOG.error(String.format("error routing document %s %s %s", approverId, document.getDocumentId(), action));
            LOG.error(e, e);
            saveException(document, action, e); //this is what I want
        }
    }

The saveException() method simply creates an objects and saves it to a table.

Now according to Spring documentation about transactions, This rollback happens by default where the exception is a runtime exception and I have confirmed that the rollback works correctly but it's somehow not allowing my code to run and save the information I need or rolling that one back too (?).

Any help or hints to a solution is appreciated.

Was it helpful?

Solution

This is not an uncommon use case: the transaction failed and we want to roll it back, but we would still like to update some monitoring database table with the error cause.

For doing this in a Spring application use REQUIRES_NEW propagation of the @Transactional annotation.

@Transactional REQUIRES_NEW propagation

For doing this, create an application state tracking service, and annotate it with REQUIRES_NEW transaction propagation.

Each method in the state tracking service will run in it's own separate transaction, so when the transaction on the main business method rolls back, the state tracking information will still be available on the database.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top