I have three different third-party services and I try to call all of them in a single handle method. Also, I want to handle rollback operation. But I'm not sure about implementation. Here is my code:
void handle() {
service1.create();
callService2OrRollback();
callService3OrRollback()
}
void callService2OrRollback() {
try {
service2.create();
} catch(Exception e) {
service1.delete();
throw e;
}
}
void callService3OrRollback() {
try {
service3.create();
} catch(Exception e) {
service1.delete();
service2.delete();
throw e;
}
}
Is there a better way to implement rollback mechanisms? BTW, I'm using java and spring-boot.
Inspired from Temporal: https://temporal.io/blog/saga-pattern-made-easy
public final class Saga {
private final List<Runnable> compensationOps = new ArrayList<>();
public void addCompensation(Runnable runnable) {
compensationOps.add(runnable);
}
public void compensate() {
for (Runnable runnable : compensationOps) {
try {
runnable.run();
} catch (Exception e) {
log.error("Unexpected error on compensation and ignored sakes of remaining rollbacks");
}
}
}
}
Example Usage:
Saga saga = new Saga();
try {
triggerFirstService();
saga.addCompensation(() -> addFirstServiceRollback());
triggerSecondService();
saga.addCompensation(() -> addSecondServiceRollback());
triggerFinalService();
} catch(Exception ex) {
saga.compensate();
}