Handle fetch errors properly in JavaScript
Advanced · 4 min read
Almost every app loads data from a server: products, messages, bus routes. In the browser you do that with fetch. Getting data when everything works takes two lines. The hard part is what happens when it doesn't, because fetch has its own idea of what counts as an error, and it's not the one most people expect.
In this tutorial you will load a list of routes with fetch, and handle three different failures with three different messages: no connection, a server that answers with an error, and a reply that isn't valid JSON. You should know what an object is and have used try and catch. Promises and await are explained briefly below.
Promises and await, in short
Asking a server for data takes time, so fetch doesn't hand back the data straight away. It hands back a promise: an object that will later either resolve (succeed, with a value) or reject (fail, with an error).
Inside a function marked async, writing await in front of a promise pauses that function until the promise settles. If it resolves, you get the value. If it rejects, await throws the error, and a try/catch around it can catch it.
What fetch counts as an error
This is the whole exercise:
fetchrejects only when the request couldn't be made at all: no internet connection, a server name that doesn't exist, or a request the browser blocked for security reasons.- If the server answers, even with "404 Not Found" or "500 Internal Server Error",
fetchresolves. The answer comes back as a response object whoseokproperty isfalse.
So a try/catch on its own misses every server error. You need it, and you also need to check response.ok.
For this lesson, fetch answers from a small pretend server with five addresses: /routes works, /missing gives 404, /broken gives 500, /malformed answers 200 with broken JSON, and /offline fails as if the network were down.
Here is the exercise. Try it yourself first, or read on and we will build it together.
18 Fetch with real error handling
hardFetch data, handle a network failure and a bad status differently, and show the result. The trap is what fetch treats as an error.
Stuck? Three hints, smallest first
- 1.
fetchdoes not reject on 404 or 500. It resolves, andresponse.okis false. - 2. It rejects only when the request could not be made at all — no connection, DNS failure, CORS.
- 3. So you need a
try/catchand anif (!response.ok). One is not enough.
Step 1: the version most people write first
async function load(url) {
try {
const response = await fetch(url);
const data = await response.json();
return `loaded ${data.length} route(s)`;
} catch (error) {
return 'Could not reach the server.';
}
}
console.log(await load('/routes')); // loaded 2 route(s)
console.log(await load('/broken')); // Could not reach the server.
response.json() reads the body and parses it as JSON. It returns a promise too, hence the second await.
The first call works. The second one blames the connection, but the connection was fine: the server answered with a 500 error. What went wrong is that fetch resolved, our code went on to response.json(), and the error page's text ("server error") isn't JSON, so parsing threw a SyntaxError. The catch caught that, and showed the wrong message.
Step 2: look at a 404 response
const response = await fetch('/missing');
console.log(response.ok, response.status, response.statusText); // false 404 Not Found
No error was thrown. The promise resolved with a response that says, through ok, "this didn't go well". ok is true only for statuses from 200 to 299. statusText is the short description after the number. Over newer versions of HTTP, browsers often leave it empty, so use it only for display and make decisions with status.
Step 3: check response.ok
async function load(url) {
try {
const response = await fetch(url);
if (!response.ok) {
return { state: 'http', status: response.status, message: `The server answered ${response.status} ${response.statusText}.` };
}
const data = await response.json();
return { state: 'ok', count: data.length, data };
} catch (error) {
return { state: 'offline', message: 'Could not reach the server. Check your connection.' };
}
}
console.log((await load('/broken')).message); // The server answered 500 Internal Server Error.
console.log((await load('/offline')).message); // Could not reach the server. Check your connection.
Now a server error stops before response.json() and gets its own message, with the status number. Only a real network failure reaches the catch.
Returning an object with a state instead of a sentence lets the rest of the page decide what to do: show the data, offer a "Try again" button, and so on.
Step 4: a reply that isn't JSON
There's one more case. The server says 200 OK, but the body is broken:
console.log((await load('/malformed')).state); // offline
Wrong again. The SyntaxError from response.json() lands in the same catch as a network failure. The error tells us which it was: a broken body throws a SyntaxError, so check for it with instanceof.
async function load(url) {
try {
const response = await fetch(url);
if (!response.ok) {
return { state: 'http', status: response.status, message: `The server answered ${response.status} ${response.statusText}.` };
}
const data = await response.json();
return { state: 'ok', count: data.length, data };
} catch (error) {
if (error instanceof SyntaxError) {
return { state: 'malformed', message: 'The server answered 200, but the body was not valid JSON.' };
}
return { state: 'offline', message: 'Could not reach the server. Check your connection.' };
}
}
for (const url of ['/routes', '/missing', '/broken', '/malformed', '/offline']) {
const result = await load(url);
console.log(url, '->', result.state);
}
// /routes -> ok
// /missing -> http
// /broken -> http
// /malformed -> malformed
// /offline -> offline
Three kinds of failure, three messages, and the person reading them knows what actually happened.
The full solution
The full solution can't use the network, so its fetch answers from the same routing table as this lesson. Like the real one, it resolves for 404 and 500 and rejects only for the network failure. Its checks confirm a good response loads usable data, a 404 resolves with ok false and is reported as an HTTP error with its status, a 500 is handled the same way, a network failure gets its own message, broken JSON on a 200 is its own case, and an unknown address answers 404 instead of throwing. Press Run, then try each button in the live demo.
allow-scripts only, so it cannot reach this page.const fetch = makeFetch({
'/routes': { status: 200, body: '[{"from":"Ojota","to":"Abuja"},{"from":"Ojota","to":"Kano"}]' },
'/missing': { status: 404, body: 'not found' },
'/broken': { status: 500, body: 'server error' },
'/malformed': { status: 200, body: '{not json' },
'/offline': 'network-error',
});
const out = el('pre', { id: 'out' });
document.body.appendChild(out);
/* Three distinct failures, three distinct messages:
the request never happened -> fetch REJECTS
the server answered with an error -> fetch RESOLVES, response.ok is false
the body was not what we expected -> response.json() throws */
async function load(url) {
try {
const response = await fetch(url);
if (!response.ok) {
return { state: 'http', status: response.status, message: `The server answered ${response.status} ${response.statusText}.` };
}
const data = await response.json(); // throws on malformed JSON
return { state: 'ok', count: data.length, data };
} catch (error) {
if (error instanceof SyntaxError) {
return { state: 'malformed', message: 'The server answered 200, but the body was not valid JSON.' };
}
return { state: 'offline', message: 'Could not reach the server. Check your connection.' };
}
}
for (const url of ['/routes', '/missing', '/broken', '/malformed', '/offline']) {
const result = await load(url);
console.log(url.padEnd(11), '->', result.state.padEnd(10), result.message ?? `${result.count} route(s)`);
}
const ok = await load('/routes');
const notFound = await load('/missing');
const serverError = await load('/broken');
const malformed = await load('/malformed');
const offline = await load('/offline');
// The heart of it: a 404 RESOLVES.
const raw404 = await fetch('/missing');
console.log('a 404 response: ok =', raw404.ok, ', status =', raw404.status, '<- it resolved');
Output
17 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 17 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a good response loads', ok.state, 'ok');
test('with the parsed data', ok.count, 2);
test('and the data is usable', ok.data[0].to, 'Abuja');
test('a 404 does NOT reject', raw404.status, 404);
test('it resolves with ok false', raw404.ok, false);
test('so it is reported as an http error', notFound.state, 'http');
test('with the status in the message', notFound.message, 'The server answered 404 Not Found.');
test('a 500 is handled the same way', serverError.state, 'http');
test('with its own status', serverError.status, 500);
test('a network failure DOES reject', offline.state, 'offline');
test('and gets a different message', offline.message.includes('connection'), true);
test('the two failures are told apart', notFound.state === offline.state, false);
test('malformed JSON on a 200 is its own case', malformed.state, 'malformed');
test('and is not mistaken for a network problem', malformed.message.includes('connection'), false);
test('a 200 response is ok', (await fetch('/routes')).ok, true);
test('an unknown route answers 404 rather than throwing', (await fetch('/nowhere')).status, 404);
test('every request was recorded', fetch.calls.length > 5, true);
Adapted: fetch here answers from a local routing table, because this course loads nothing over the network. The demo uses the same technique so it works offline too.
The thing to take away: fetch rejects only when the request could not be made — no connection, DNS failure, blocked by CORS. A 404 or a 500 is a successful HTTP exchange as far as fetch is concerned, so the promise resolves and response.ok is false. The assertions check raw404.status is 404 on a resolved response, which is the whole point.
So a try/catch alone is not error handling. Without if (!response.ok), a 500 flows into response.json(), which throws a SyntaxError on the HTML error page the server returned, and your catch block reports "check your connection" for a working connection. Three failure modes, three messages, and the assertion that two of them differ is what stops them collapsing into one unhelpful line.
Common mistakes
- Relying on
try/catchalone. A 404 or 500 doesn't throw. Checkresponse.okbefore reading the body. - Calling
response.json()on an error response. Error pages are usually not JSON, so it throws aSyntaxErrorthat looks like a network problem. - One message for every failure. "Check your connection" for a server error sends the user looking for the wrong problem.
Try it yourself
- Show "loading..." on the page before the
fetch, and replace it with the result afterwards. - When the state is
'offline', show a "Try again" button that callsloadagain. - Give a 401 status its own message, "Please sign in", before the general HTTP error.