Skip to content

Error handling & compensation

Activities fail — networks blip, label printers go offline. PgWorkflows retries activities for you, and when a workflow fails permanently partway through, ctx.OnFailure runs the compensations you registered, in reverse, so completed side effects get undone.

Register a compensating activity right after the step it undoes. If a later step fails permanently, the registered compensations run.

var reservation = await ctx.Activity(
(CheckoutActivities a) => a.ReserveInventory(input.UserName, itemName),
cancellationToken
);
await ctx.OnFailure(
(CheckoutActivities a) => a.ReleaseInventory(reservation.ReservationId),
cancellationToken
);
var payment = await ctx.Activity(
(CheckoutActivities a) => a.ChargePayment(input.UserName, input.Amount),
cancellationToken
);
await ctx.OnFailure(
(CheckoutActivities a) => a.RefundPayment(payment.PaymentId),
cancellationToken
);
// If this throws permanently, the refund and the release both run.
await ctx.Activity(
(CheckoutActivities a) => a.CreateShipment(input.UserName, itemName),
cancellationToken
);