Skip to content
jshacks.dev
APIs

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.

1 min read
Summarize in AI

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.

fetch-json.jsJavaScript
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);
}
Text
1
HTTP 404 Not Found

res.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.

Also inBrowser
Taggedfetch
Share

More snippets

Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.