SyntaxStudy
Sign Up
JavaScript Intermediate 4 min read

Fetch Error Handling

Fetch Error Handling

Network errors throw; HTTP errors do not. Build a wrapper that normalises both into rejections.

Example
async function apiFetch(url, opts = {}) {
  const res = await fetch(url, opts);
  if (!res.ok) {
    const body = await res.text().catch(() => "");
    throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status, body });
  }
  return res.json();
}
Pro Tip

Wrapping fetch in a helper centralises error normalisation and avoids repeating if (!res.ok) everywhere.