Skip to content
jshacks.dev
Async

How to Retry Only on Specific Errors in JavaScript

Retry only on specific errors in JavaScript: classify failures as transient or permanent, honor Retry-After and stop retrying on bad input or unsafe writes.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Redis, Apache Kafka, RabbitMQ and Node.js logos.

A retry loop that retries everything is a bug with good intentions. Retrying a request that failed because the password was wrong locks the account faster. Retrying one that failed with a validation error repeats the same failure five times and delays the real message. Retrying a payment whose first attempt may have succeeded charges the card twice. Retries help only for transient failures, the ones that go away if you wait a moment. This post shows how to retry only on specific errors in JavaScript: how to classify failures, how to write the classifier for fetch, for Node.js system errors and for your own error types, and how to honor the server's own advice in a Retry-After header. It builds on retrying a failed promise with backoff, which supplies the loop, and all the examples run on Node.js 24.

Transient and permanent failures

A failure is transient when the same request could succeed later without any change: a dropped connection, a timeout, a server overloaded for a few seconds, a rate limit that resets. A failure is permanent when repeating the request cannot help: a malformed request, missing authentication, a resource that does not exist, a business rule that rejects the input. The first group deserves retries and the second deserves an immediate, clear error. Everything else is a judgment call that depends on the operation, and the safe default for an unknown error is not to retry.

A predicate on the retry loop

The cleanest way to add the rule is a function, shouldRetry(error, attempt), that the loop calls after each failure. The loop stays generic, and each call site supplies its own policy.

retry.jsJavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export async function retry(task, { attempts = 3, baseMs = 50, shouldRetry } = {}) {
  let lastError;
  for (let attempt = 1; attempt <= attempts; attempt++) {
    try {
      return await task(attempt);
    } catch (error) {
      lastError = error;
      const canRetry = attempt < attempts && shouldRetry(error, attempt);
      if (!canRetry) throw error;
      await sleep(Math.random() * baseMs * 2 ** (attempt - 1));
    }
  }
  throw lastError;
}

If the predicate returns false, the original error is rethrown at once, with its own message and stack, so a permanent failure reaches the caller on the first attempt. The predicate is required here, because a retry helper whose default is "retry everything" invites the very bug this post is about.

Classify errors from fetch

fetch rejects only for network failures. An HTTP error status resolves, so the code must turn it into an error before the loop sees it. Give those errors a class that carries the status, then classify by status code.

http.jsJavaScript
export class HttpError extends Error {
  constructor(status, retryAfterMs = null) {
    super(`HTTP ${status}`);
    this.name = "HttpError";
    this.status = status;
    this.retryAfterMs = retryAfterMs;
  }
}

const RETRYABLE_STATUS = new Set([408, 425, 429, 500, 502, 503, 504]);

export function isTransient(error) {
  if (error instanceof HttpError) return RETRYABLE_STATUS.has(error.status);
  if (error instanceof TypeError) return true; // fetch network failure
  return false;
}

console.log(isTransient(new HttpError(503)));
console.log(isTransient(new HttpError(404)));
console.log(isTransient(new TypeError("fetch failed")));
console.log(isTransient(new Error("unknown")));
Text
true
false
true
false

A 503 or 429 may pass, so it is retried. A 404 or 400 will not, so it is not. A TypeError from fetch signals a network-level failure, such as a refused connection or a DNS error, which is transient. Plain unknown errors are not retried, following the safe default. Status 501 and 505 are left out on purpose, because "not implemented" is not going to change on its own.

Classify Node.js system errors

Errors from sockets and files carry a code property. Some codes name transient conditions.

system-errors.jsJavaScript
const TRANSIENT_CODES = new Set([
  "ECONNRESET",
  "ETIMEDOUT",
  "ECONNREFUSED",
  "EAI_AGAIN",
  "EPIPE",
]);

export function isTransientSystemError(error) {
  return typeof error?.code === "string" && TRANSIENT_CODES.has(error.code);
}

const reset = Object.assign(new Error("socket hang up"), { code: "ECONNRESET" });
const missing = Object.assign(new Error("no such file"), { code: "ENOENT" });
console.log(isTransientSystemError(reset), isTransientSystemError(missing));
Text
true false

ECONNRESET and ETIMEDOUT are classic transient failures. ENOENT means the file does not exist and will not appear because you waited, so it is permanent. Treat ECONNREFUSED with thought: during a deploy the service may be restarting and come back in seconds, so retrying is reasonable, while for a service that is down for good the delay only postpones the error.

Honor Retry-After

When a server returns 429 or 503, it may tell you how long to wait in a Retry-After header, as a number of seconds or an HTTP date. Using that value is better than guessing, and ignoring it risks being blocked. Parse the header when you build the HttpError, and let the loop prefer it to its own delay.

retry-after.jsJavaScript
export function parseRetryAfter(value, now = Date.now()) {
  if (!value) return null;
  const seconds = Number(value);
  if (Number.isFinite(seconds)) return seconds * 1000;
  const date = Date.parse(value);
  return Number.isNaN(date) ? null : Math.max(0, date - now);
}

console.log(parseRetryAfter("3"));
console.log(parseRetryAfter("Wed, 21 Oct 2026 07:28:03 GMT", Date.parse("Wed, 21 Oct 2026 07:28:00 GMT")));
console.log(parseRetryAfter("soon"));
Text
3000
3000
null

The function returns milliseconds, or null when the header is missing or not understood. In the loop, wait error.retryAfterMs ?? computedDelay, and cap it, so a server that sends Retry-After: 86400 does not block your process for a day without your agreement.

Never retry unsafe writes blindly

Idempotence decides whether a retry is safe. A GET can be repeated. A PUT that sets a value to a given content usually can. A POST that creates a record or moves money cannot, unless the server accepts an idempotency key that it uses to recognize a repeat. If the operation is not idempotent, retry only on failures that happen before the request is sent, such as a connection refused, where you know the server never saw it. After a timeout or a reset you do not know whether the first attempt succeeded, so a blind retry may do it twice.

Putting the predicate to use

use.jsJavaScript
import { retry } from "./retry.js";
import { HttpError, isTransient } from "./http.js";

let calls = 0;
const task = async () => {
  calls += 1;
  throw new HttpError(404);
};

try {
  await retry(task, { shouldRetry: (error) => isTransient(error) });
} catch (error) {
  console.log(`${error.message} after ${calls} call`);
}
Text
HTTP 404 after 1 call

The 404 was classified as permanent, so the helper made a single call and passed the error through. With a 503 in its place, the same code would make three calls, with growing waits between them.

Giving callers a say

Different callers of the same function may want different rules. A background sync job can retry for minutes, while a user-facing request should give up after one extra try. Keep the classifier separate from the loop and let the caller choose both the predicate and the numbers. A function that wraps an API client can accept { retry: { attempts, shouldRetry } } in its options and default to a conservative policy. That keeps the common case short and leaves room for exceptions without a second implementation.

Think about observability too. Log every retry with the attempt number, the error class and the delay, at a level that is quiet in normal operation. When an incident happens, the retry log shows whether the system recovered by itself, how long it took and which failures it considered transient. Counting retries per error type also reveals misclassification: a spike of retries on a status you thought permanent means the rule is wrong.

Where classification goes wrong

The most common mistake is to retry on any Error, because the catch block does not distinguish. The second is to classify by message text, such as checking whether error.message includes "timeout", which breaks when a library rewords its messages or when the text is localized. Prefer stable properties: a class, a numeric status, a code. The third is to forget the errors that your own code throws: a validation helper that throws a plain Error looks the same to the predicate as a network failure. Give your own errors distinct classes, so the predicate can recognize and exclude them.

A subtler mistake is to treat a timeout from your own AbortSignal.timeout as retryable without thinking. If the timeout exists because the whole operation has a deadline, retrying after it fires exceeds the deadline. Check the signal before each attempt, and stop when it has aborted, as in the cancelable retry in the retry guide.

Testing the policy

The classifier is a pure function, so test it as a table: each row is an error and the expected answer, with one row per status code and system code you care about, plus unknown shapes such as null, a string and an object without a code. Then test the loop with a stub that throws a sequence of errors, and assert on the number of calls: a permanent error should produce exactly one, a transient error followed by success should produce two, and a transient error that never clears should produce the attempt limit. Use short base delays or fake timers, so the suite stays fast.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.