JavaScript fetch with async/await: proper error handling
The surprise that bites everyone once: fetch only rejects its promise on network failure. A 404 or 500 response still resolves normally. If you treat resolution as success, your app quietly processes error pages as data. This guide is the correct pattern, per MDN's Using Fetch.
The shape of a safe call
async function getData(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
}
Three ideas here, all from MDN's guide: await fetch() gives you a Response as soon as headers arrive, response.ok is the reliable success check (true for 200-299), and response.json() parses the body asynchronously.
Catch network errors and HTTP errors separately
try {
const data = await getData('/api/orders');
render(data);
} catch (err) {
showError(err.message);
}
Network failures (offline, DNS, CORS block) land in the catch via fetch's own rejection; HTTP error statuses land there via your !response.ok throw. One try/catch, two distinct failure kinds, both handled.
Add a timeout with AbortController
fetch has no built-in timeout. MDN's answer is AbortController:
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 8000);
try {
const response = await fetch(url, { signal: ctrl.signal });
// ...
} finally {
clearTimeout(timer);
}
After 8 seconds the request aborts and fetch rejects, which your catch turns into a friendly error instead of an eternal spinner.
Sending JSON
await fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ item: 'keyboard', qty: 2 })
});
Common mistakes
- Calling
response.json()before checkingresponse.ok, then parsing an HTML error page. - Forgetting that
response.json()is async and returning its promise as if it were data. - No timeout, so a hung server hangs your UI forever.
Backend side: build the REST API with Express, and PHP cURL POST for the same pattern server-side.
