The Fetch API rejects its promise only for network-level errors. These include issues like the server being unreachable, no internet connection, or CORS restrictions. It does not reject the promise for HTTP response codes like 404 (Not Found)
or 500 (Internal Server Error)
. As long as the request completes, the Fetch API considers the response successful, even if the server returns an error status.
So without explicitly checking HTTP status codes, your application might treat these error responses as valid, causing unintended behavior.
The response.ok
property provides a simple way to verify if the HTTP status code falls within the successful range (200–299)
. If the status code is outside this range, the response can be considered a failure.
In the above code,
-
Thefetch()
method makes a GET request to https://jsonplaceholder.typicode.com/invalidEndpoint
, a non-existent endpoint, resulting in a 404 Not Found
status from the server.
-
The .then()
block runs because fetch treats the network request as successfully resolved, even though the server returned a 404
error. It logs the response object, which includes details like status: 404
and ok: false
.
-
The .catch()
block does not execute since no network-level error occurred, the server was reachable, and the request completed successfully.
Improving Error Handling with response.ok