Fetch JSON and handle HTTP errors
Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.
A fetch call that gets a 404 still resolves. If you call res.json() on an error page you get a confusing parse error, or worse, an error object you treat as data.
async function getJson(url) {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`);
}
return res.json();
}
try {
const data = await getJson('https://jsonplaceholder.typicode.com/todos/1');
console.log(data.id);
await getJson('https://jsonplaceholder.typicode.com/nope');
} catch (error) {
console.log(error.message);
}1
HTTP 404 Not Foundres.ok is true for status codes 200 to 299. The promise returned by fetch rejects only when the request cannot complete at all, such as a DNS failure, a refused connection or an abort. Reading the status is on you, as the Fetch API reference explains.
Servers often send a JSON error body with a 4xx status; if you need it, read await res.json() inside the !res.ok branch before throwing. HTTP/2 connections have an empty statusText.