ArticleZip > Fetch Reject Promise And Catch The Error If Status Is Not Ok

Fetch Reject Promise And Catch The Error If Status Is Not Ok

When working with asynchronous operations in JavaScript, handling promises is crucial to ensure smooth and efficient code execution. A common scenario developers encounter is fetching data from a server and dealing with errors appropriately. This is where the `fetch` API, `Promise`, `reject`, and `catch` come into play to streamline the process and manage errors effectively.

To begin, the `fetch` API is a modern and powerful interface for fetching resources across the network. It returns a promise that resolves to the `Response` to that request, whether it is successful or not. When making a `fetch` request, it's essential to check the `status` property of the `Response` to determine if the request was successful.

When the server responds with a non-success status code, the promise returned by `fetch` does not reject automatically. This is where we can use the `reject` method to explicitly reject the promise if the status is not "OK." By chaining a `.then()` method after the `fetch` call, we can perform this check and handle the promise accordingly.

Here's an example of how you can utilize `fetch`, `Promise`, `reject`, and `catch` to handle errors when the status is not "OK":

Javascript

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      return Promise.reject('Error retrieving data');
    }
    return response.json();
  })
  .then(data => {
    // Handle the data when the request is successful
  })
  .catch(error => {
    // Catch and handle the error when the request fails or the status is not "OK"
    console.error(error);
  });

In this code snippet, the initial `fetch` call is made to retrieve data from `https://api.example.com/data`. The subsequent `.then()` block checks if the response status is not "OK" using the `response.ok` property. If the status is not "OK," the promise is explicitly rejected with an error message.

By explicitly rejecting the promise, we ensure that the error is caught in the `.catch()` block, where you can handle it accordingly, such as logging the error or displaying a user-friendly message.

Using `fetch`, `Promise`, `reject`, and `catch` in this manner enhances the robustness of your code by gracefully handling errors and providing a clear path for error recovery or notification. Remember to leverage these tools effectively to create more reliable and maintainable code when working with asynchronous requests in JavaScript.

×