Retry Operation Wrapper With Error Filters

Wrap flaky operations with the retry package using predicate-based retries, exponential factors, randomization, and per-operation abort signals.

JavascriptResilience

Code

javascriptsnippet
27 lines
import retry from 'retry';

async function fetchWithRetry(url, { signal } = {}) {
  const operation = retry.operation({
    retries: 5,
    factor: 2,
    minTimeout: 500,
    maxTimeout: 8000,
    randomize: true,
  });

  return new Promise((resolve, reject) => {
    operation.attempt(async (currentAttempt) => {
      try {
        const res = await fetch(url, { signal });
        if (res.status >= 500) throw new Error('upstream ' + res.status);
        resolve(await res.json());
      } catch (err) {
        if (operation.retry(err)) return;
        reject(operation.mainError());
      }
    });
  });
}

const data = await fetchWithRetry('https://api.example.com/pricing');
console.log('plans:', data.plans.length);

What the code does

Retry Operation Wrapper With Error Filters is built around the function fetchWithRetry.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Instead of silently continuing, the code raises Error at the guard.

The return value is newly constructed — inputs are never handed back.

Watch out for

  • Dependency check: retry — not built-in, must be present in the project.
  • A browser is the runtime here: fetch are not available in Node.
  • The guard res.status >= 500 short-circuits the flow with an early throw when its condition holds.

Applying it

Entry signature: async function fetchWithRetry(url, { signal } = {})

Output lines are prefixed (plans:), making each step’s effect easy to spot.

Statements that matter

const data = await fetchWithRetry('https://api.example.com/pricing');
if (res.status >= 500) throw new Error('upstream ' + res.status);
const res = await fetch(url, { signal });

Interactive Tools for This Topic

FAQ

Does `fetchWithRetry` modify its input?
No mutation happens — the function reads its input and returns a new value.
How does the snippet fail?
The code refuses to continue: `Error` is thrown while the state is still recoverable.
What does this need from the package registry?
These are real dependencies: `retry`. Without it the snippet will not load.