
A dashboard shows a success message even though the API returned 404. The request sits inside try/catch, so why did the error handler never run? With JavaScript fetch, receiving an HTTP error response is different from failing to receive a response. I would check that boundary before adding retries or changing the server.
Three different checkpoints
Think of a JSON request as three checks: did fetch produce a Response, does its HTTP status match your contract, and can the body be parsed and used? Passing an earlier check does not prove the later ones passed.
- Request failure: a network problem or another fetch rejection can enter catch without a usable Response.
- HTTP failure: an accessible 404 or 500 response normally fulfills fetch. Your code must inspect the status.
- Body failure: even a 200 response can contain HTML, malformed JSON or data with the wrong fields.
Response.ok is true for statuses 200 through 299. It is a useful first gate, not a guarantee that the application received the object it needs.
A small reader with an explicit contract
This example is for a same-origin GET endpoint that promises a JSON body on every successful response. It intentionally treats an empty successful response as an error, rather than quietly inventing an empty object.
async function readJSON(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
}
async function loadItems() {
try {
const data = await readJSON('/api/items');
if (!Array.isArray(data.items)) {
throw new Error('Expected an items array');
}
// Render the validated items here.
} catch (error) {
// Show a useful failure state, not success.
console.error(error);
}
}
The status check happens before JSON parsing, so a 404 HTML error page does not get mislabeled as only a JSON problem. The await on response.json() also keeps parsing failure inside the caller's awaited operation. The shape check is deliberately narrow: real applications may need validation of every item, not merely the array.
What I checked locally
I ran Node's fetch against a temporary local HTTP server with four routes. A 404 JSON route fulfilled fetch with ok=false, and its body was still parseable JSON. A 200 HTML route fulfilled with ok=true, then JSON parsing raised SyntaxError. A 204 empty route also had ok=true and failed JSON parsing. A 200 JSON route completed both steps.
These are small behavior checks, not a browser compatibility test or a CORS test. They show why neither a resolved promise nor parseable JSON alone is a success rule. If your API legitimately returns 204, handle that documented case before parsing, for example by returning null and having the caller explicitly accept it.
Diagnose without hiding the real error
In the browser's Network panel, inspect the status, final request URL, response content type and response preview. A login page returned as HTML can explain an unexpected JSON token. Content-Type is a useful clue, but a JSON label does not prove valid JSON or the right schema.
Do not use no-cors as an error fix. MDN explains that a cross-origin no-cors response is opaque: JavaScript cannot read its body or headers, and its status is 0. That does not turn it into a usable JSON response.
Keep diagnostic details private. Avoid displaying raw server bodies or logging tokens and personal data. Finally, decide recovery from the actual failure and API contract, rather than retrying every exception. A catch block is where failure becomes visible; it is not evidence that every failure has the same cause.
Comments
Post a Comment