I've always been an avid user of Axios for data fetching, but I recently decided to use the Fetch API instead. While exploring it, I encountered a subtle but significant difference that I thought was worth sharing.
Let’s start with this snippet of code. What do you think it logs?
try{ //this returns a 404 error const res = await fetch("randomapi....") console.log("successful") }catch(err){ console.log("failed", err) }
If you guessed it would log "failed" along with the error object to the console, you’re not alone—I thought the same thing until recently. However, that’s not how Fetch works!
Here’s the catch: even if the Fetch request receives a 404 or 500 status code, it doesn’t throw an error and doesn’t trigger the catch block. Instead, the fetch function resolves the promise, leaving it to you to check whether the response was successful.
To correctly handle errors with Fetch, you need to explicitly check the res.ok property, like so:
try{ //returns 404 error const res = await fetch("randomapi") if(!res.ok){ throw new Error("fetch request failed") } console.log("successful") let data = await res.json() console.log(data) }catch(err){ console.log(err) }
With this approach, if the response status is outside the successful range (200–299), the throw statement is executed, and the error is caught in the catch block.
Why Does This Happen?
Unlike Axios, Fetch doesn’t consider HTTP response codes outside of the 2xx range to be errors. Instead, it treats all HTTP responses, successful or not, as fulfilled promises. This design choice gives developers more control but also requires extra effort to handle errors correctly.
Understanding response.ok
The response.ok property is a boolean that evaluates to truefor HTTP status codes between 200and 299. For any other status code, it evaluates to false. This makes it an easy and reliable way to check whether your fetch request was successful.
For example:
You can also access the status code directly using response.status if you need more granular error handling, like distinguishing between a client-side error (4xx) and a server-side error (5xx).
Thanks for reading and I hope this helps someone out there!
The above is the detailed content of Understanding the Importance of res.ok in Fetch API. For more information, please follow other related articles on the PHP Chinese website!