Intermediate 8 min

Fetch, HTTP errors, and cancellation

Fetch requests data and resolves to a response whose status you can inspect.

How it works

There are two opportunities for failure. The request may not reach a server at all. Or the server may reply that something went wrong. Use a catch for rejected requests and inspect the HTTP status on responses that arrive. A superseded search can also be aborted so an older response does not overwrite a newer view.

Walk through an example

Check response.ok before reading expected success data. To let a caller stop a request, pass the signal from an AbortController into fetch.

What to watch for

Fetch generally resolves for HTTP errors such as 404. Network problems or cancellation can reject the Promise. Handle both paths.

Code example

async function loadJson(url, signal) {
  const response = await fetch(url, { signal });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

Check your understanding

Does fetch normally reject solely because the response is 404?

See the example and explanation
Worked example
Given A server replies with HTTP 404.
Answer No.

You receive a response with ok false. The caller can raise its own error or show a missing-item message.

Open practice problem
Next lessonMap and Set in JavaScript