HTTP Status Code Classifier

Classify HTTP status codes by class and expose retryable, cacheable, success and error flags for client logic.

JavascriptResilience

Code

snippet
const RETRYABLE = new Set([408, 425, 429, 500, 502, 503, 504]);
const CACHEABLE = new Set([200, 203, 204, 206, 300, 301, 308, 404, 410]);

export function classifyStatus(status) {
  if (!Number.isInteger(status) || status < 100 || status > 599) {
    throw new RangeError("status must be a three-digit HTTP status code");
  }
  const group = Math.floor(status / 100);
  const labels = {
    1: "informational",
    2: "success",
    3: "redirect",
    4: "client-error",
    5: "server-error",
  };
  return {
    status,
    group,
    label: labels[group],
    success: group === 2,
    redirect: group === 3,
    error: group >= 4,
    retryable: RETRYABLE.has(status),
    cacheable: CACHEABLE.has(status),
  };
}

export function isRetryableStatus(status) {
  return classifyStatus(status).retryable;
}