I have a JPA transaction like the following (Using controller advice to catch exceptions)
@Transactional
public void save(MyObj myObj) {
// Attempt to save the object
this.myRepo.save(myObj)
// After it saves, call my audit log service to record the change
this.myAuditLogService.logChange(myObj)
}
Works fine, but the problem is if the save fails and throws an exception, it still calls the audit log service, and then throws an exception afterwards. Causing erroneous audit entries to be created.
Expected Flow
- Call save function
- Save fails
- Transaction stops and rolls back
- Controller advice catches the exception
Actual Flow
- Call save function
- Save fails
- Audit log service is called
- Transaction rolls back
- Controller advice catches the exception