fetch() resolves on 404 and 500, so catch never runs
catch never runs on a 404 or 500 responseShort answer
A fetch promise only rejects when the request itself fails, such as a network error or an abort. A 404 or 500 reply still counts as a response and resolves normally. Check response.ok or response.status after every call and throw your own error, then handle both kinds of failure in one catch.
Fix it fast
1Find out which cause you have
Log the status and the ok flag of the response before reading its body. If ok is false and the code went on anyway, the first cause applies.
const response = await fetch(url); console.log(response.status, response.ok);2Match what you see, then jump to its fix
What does the error look like?
catch never runs on a 404 or 500 response
Cause 1 of 2
The code never checks the response status
1Check
MDN states that a fetch promise does not reject for HTTP error codes such as 404 or 504. A handler must check Response.ok or Response.status. ok is true for statuses 200 to 299.
grep -rn "fetch(" src/2Fix
Throw an error when ok is false, before you parse the body. Keep this in one helper so every call behaves the same.
async function getJson(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
}3Verify
Call it with a URL that returns 404 and watch the error arrive in catch.
getJson('/does-not-exist').catch((err) => console.log('caught:', err.message));Confirmed by developer.mozilla.org
Cause 2 of 2
Only network and request failures are caught, and they look different
1Check
MDN lists what makes fetch reject: an invalid URL, URL credentials, invalid options, a blocked permissions policy, a network error, and AbortError after AbortController.abort().
console.log(error.name, error.message)2Fix
Tell the kinds of failure apart in catch, so an abort that you caused on purpose is not shown to the user as an error.
try {
const data = await getJson('/api/items', { signal });
setItems(data);
} catch (error) {
if (error.name === 'AbortError') return; // you cancelled it
setError(error.message); // network or HTTP failure
}3Verify
Turn the network off in dev tools: the message appears. Navigate away: no message.
npm run devConfirmed by developer.mozilla.org
How do I stop it coming back?
- Wrap fetch once in a helper that checks response.ok, and use only the helper.
- Keep an error state next to loading and data state in your components.
- Pass an AbortController signal from useEffect and abort in its cleanup.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- WorkforceA field app, an admin console and a self-hosted Node.js server for push and reconciliation.
Related fixes
Web apps
fetch() throws TypeError: Failed to fetch in the browser
Uncaught (in promise) TypeError: Failed to fetch
Failed to fetch means the request never produced a response the browser would hand to your code.
4 causes, each with a fixWeb apps
React shows Attempted import error when importing a component or function
Attempted import error:
The build found the file but not the name you asked for.
2 causes, each with a fixWeb apps
AxiosError Network Error with code ERR_NETWORK in a React app
Network Error
ERR_NETWORK means the request produced no readable response.
4 causes, each with a fixWeb apps
Axios get works with a URL string but ignores the object passed as the second argument
The server log shows a GET with no query string
axios.get takes a URL and an optional config object.
3 causes, each with a fixWeb apps
Can't resolve '../axios' in a React project
Module not found: Error: Can't resolve '../axios'
A path that starts with ./ or ../ is a file path, not the axios package.
3 causes, each with a fixWeb apps
Axios returns 401 from a React app but the login works elsewhere
Error: Request failed with status code 401
A 401 means the server received the request without valid credentials.
3 causes, each with a fix