Node.js
Check HTTP status before reading fetch JSON
Fetch does not reject just because an HTTP response has a 404 or 500 status. Check response.ok before interpreting the body as successful application data.
Worked example
Node.js example · save as example.mjs and run node example.mjs
async function readJsonResponse(response) {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
}
console.log((await readJsonResponse(new Response('{"ok":true}'))).ok);
try { await readJsonResponse(new Response("missing", {status: 404})); }
catch (error) { console.log(error.message); }How it works
The example uses local Response fixtures so no external service is required. The same status check belongs immediately after an awaited fetch. HTTP failures and malformed JSON are separate errors; both need a deliberate caller response.
Limits and mistakes
An ok response may still violate your schema or return the wrong content type. Validate parsed data before trusting it. Network failures reject fetch itself, while application-specific error fields can arrive even with a successful HTTP status.
Check the result
Expect true and HTTP 404. Test a successful response containing invalid JSON to verify that body parsing errors also reach your handler.
Sources
Reference documentation for the behavior used in this guide: