Fetch Error Handling
Network errors throw; HTTP errors do not. Build a wrapper that normalises both into rejections.
Network errors throw; HTTP errors do not. Build a wrapper that normalises both into rejections.
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();
}
Wrapping fetch in a helper centralises error normalisation and avoids repeating if (!res.ok) everywhere.
More in JavaScript