Check the response before you trust it
Your request fails, but fetch resolves anyway. The server answered 404, and
you got a Response back — status set, body full of an error message, not the
record you asked for. Hand that body onward and the mistake surfaces later, far
from its cause.
fetch only rejects when the request itself fails: a dropped connection, a
DNS error, an aborted request. An HTTP error is a completed exchange. To catch it
you check the response before you trust it:
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();
response.ok is true when the status is in the 200–299 range and false
otherwise. Check it before response.json(), and treat a non-ok response as
an error — throw, or return an error result — so a 404 never flows onward as
if it were data. The status number (404, 500, …) makes the message useful.
This is the missing half of the request pattern: fetch reports transport
failures by rejecting, and you report HTTP failures by checking ok.
Export fetchPokemon from index.js. Your job is to reject when the response
is not ok, and otherwise return the first Pokémon's name from the
{ results: [...] } list the endpoint returns.
Pokémon and Pokémon character names are trademarks of Nintendo.
Challenge
A server answers 404, but fetch resolves anyway, so an error body can flow
onward as if it were data. Export an async function fetchPokemon from
index.js. It takes the URL of a Pokémon list endpoint, calls fetch,
and — before reading the body — checks response.ok. If the response is not
ok, throw an Error mentioning the status. If it is ok, return the first
Pokémon's name from the parsed { results: [...] } body.
The Test stubs fetch with an ok list response and an error response.
Pokémon and Pokémon character names are trademarks of Nintendo.