Zap Studio

Running Policies

Use BaseRetryPolicy.run for built-in orchestration with optional custom sleep behavior.

BaseRetryPolicy.run(...) is the built-in orchestration layer for retry execution.

Basic Usage

const policy = new ExponentialBackoff({
  maxAttempts: 5,
  baseDelayMs: 100,
  maxDelayMs: 2_000,
});

const result = await policy.run(async () => {
  return await doWork();
});

Custom Sleep

Use RetryRunOptions.sleep to inject a custom delay implementation. This is useful for testing and deterministic timing.

const result = await policy.run(
  async () => {
    return await doWork();
  },
  {
    sleep: async (_ms) => {
      // no delay in tests
    },
  },
);

Attempt Awareness

The execute callback receives the current attempt number.

const result = await policy.run(async (attempt) => {
  console.log("Attempt:", attempt);
  return await doWork();
});

Failure Flow

When next(...) returns shouldRetry: false, run(...) throws the error returned by onExhausted(...).

Set throwOnExhausted: false to receive a result object instead:

const result = await policy.run(
  async () => {
    return await doWork();
  },
  { throwOnExhausted: false },
);

if (!result.ok) {
  console.error(result.attempts);
} else {
  console.log(result.value);
}

Handling Terminal Errors

import { RetryError } from "@zap-studio/retry/error";

try {
  const result = await policy.run(async () => {
    return await doWork();
  });
  console.log(result);
} catch (error) {
  if (error instanceof RetryError) {
    console.error("Exhausted after attempts:", error.attempts);
  } else {
    throw error;
  }
}
Edit on GitHub

Last updated on

On this page