Implement fetchJson(fetch, url)
The single most common mistake in real API code: assuming fetch rejects on an HTTP error. It doesn't — fetch only rejects on a network failure. A 404 or 500 still resolves, with response.ok === false. Forgetting to check leads to trying to .json() an error page.
Write fetchJson(fetch, url) that:
- Calls
fetch(url). - If
response.okis false, throws an error whose message includes the status code (e.g."Request failed with status 404"). - Otherwise, returns the parsed JSON body.
const data = await fetchJson(fetch, "/api/users/1"); // { id: 1, name: "Ada" }
await fetchJson(fetch, "/api/missing"); // throws "Request failed with status 404"
fetchis passed in as an argument here (rather than using the global) so it's easy to test — that's also a genuinely good pattern for testable API code.