Async Error Classification Retry Policy

Classify async failures into retryable and fatal buckets, retrying only transient errors with backoff while surfacing permanent ones.

TypescriptResilience

Code

typescriptsnippet
50 lines
interface RetryableError extends Error {
  retryable?: boolean;
}

class PermanentError extends Error {
  retryable = false;
}

function classify(err: unknown): RetryableError {
  if (err instanceof PermanentError) return err;

  const message = err instanceof Error ? err.message : String(err);
  const transient =
    /timeout|econnreset|socket hang up|503|429/i.test(message);

  return Object.assign(
    err instanceof Error ? err : new Error(message),
    { retryable: transient },
  );
}

async function withRetry<T>(
  fn: () => Promise<T>,
  { attempts = 3, baseMs = 200 } = {},
): Promise<T> {
  let lastError: RetryableError;

  for (let i = 1; i <= attempts; i++) {
    try {
      return await fn();
    } catch (raw) {
      lastError = classify(raw);

      if (!lastError.retryable || i === attempts) {
        throw lastError;
      }
      await new Promise((r) => setTimeout(r, baseMs * 2 ** (i - 1)));
    }
  }
  throw lastError!;
}

const result = await withRetry(async () => {
  if (Math.random() < 0.7) {
    const err = new Error('upstream 503 unavailable');
    throw err;
  }
  return 'settled';
});
console.log('outcome:', result);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

outcome: settled

What the code does

classify does the bucketing — instanceof PermanentError marks fatal, while a /timeout|econnreset|socket hang up|503|429/i test on the message flags transients — and withRetry wraps the caller’s fn in the backoff loop.

The cycling part of this snippet is for (let i = 1; i <= attempts; i++). Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Caveats

  • The guard err instanceof PermanentError short-circuits the flow with an early return when its condition holds.

Using it

Entry signature: function classify(err: unknown)

The demo call throws an upstream 503 unavailable error on 70% of attempts and gets up to three tries, so the run ends with a single outcome: line — settled once a retry lands.

Key statements

await new Promise((r) => setTimeout(r, baseMs * 2 ** (i - 1)));
const result = await withRetry(async () => {
if (Math.random() < 0.7) {
const err = new Error('upstream 503 unavailable');
throw err;
}
return 'settled';
});
return await fn();

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `classify`, `withRetry` at load time.