Home > Web Front-end > JS Tutorial > Understanding the Importance of res.ok in Fetch API

Understanding the Importance of res.ok in Fetch API

Patricia Arquette
Release: 2024-12-17 14:15:16
Original
480 people have browsed it

Understanding the Importance of res.ok in Fetch API

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)
}
Copy after login

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)
}
Copy after login

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:

  • A 200 status indicates success and will set response.ok to true.
  • A 404 status (not found) or 500status (server error) will set response.ok to false.

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template