From f222361038244ef2d1f1cf9bf3d305263dc2ff6a Mon Sep 17 00:00:00 2001 From: Stephan Ewen Date: Sun, 2 Jun 2024 23:13:15 +0200 Subject: [PATCH] Fix Saga pattern to only compensate in case of a Terminal Error --- .../sagas-typescript/src/workflow_saga.ts | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/patterns-use-cases/sagas/sagas-typescript/src/workflow_saga.ts b/patterns-use-cases/sagas/sagas-typescript/src/workflow_saga.ts index b72089b1..e1ff1044 100644 --- a/patterns-use-cases/sagas/sagas-typescript/src/workflow_saga.ts +++ b/patterns-use-cases/sagas/sagas-typescript/src/workflow_saga.ts @@ -60,18 +60,16 @@ export default async (ctx: restate.Context, tripID: string) => { // await flights.confirm(tripID, flightBooking); await cars.confirm(tripID, carBooking); - } catch (e: any) { - // undo all the steps up to this point by running the compensations - for (const compensation of compensations.reverse()) { - await compensation(); - } + + } catch (e) { - // exit with an error - throw new restate.TerminalError( - `Travel reservation failed with an error: ${e.message}`, - { - cause: e, + if (e instanceof restate.TerminalError) { + // undo all the steps up to this point by running the compensations + for (const compensation of compensations.reverse()) { + await compensation(); } - ); + } + + throw e; } };