Home > Web Front-end > JS Tutorial > How to Catch Errors with Fetch Promises: Why Conditional Rejection Doesn't Work?

How to Catch Errors with Fetch Promises: Why Conditional Rejection Doesn't Work?

DDD
Release: 2024-11-13 03:36:02
Original
349 people have browsed it

How to Catch Errors with Fetch Promises: Why Conditional Rejection Doesn't Work?

Catching Errors with Fetch Promises: Conditional Rejection

In Redux applications, developers often use fetch for asynchronous requests. However, handling errors when the request fails can be challenging, especially if the request returns a non-OK status code.

Consider the following code snippet:

function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())
                .catch(error => {
                    throw(error);
                })
        });
    };
}

function status(res) {
    if (!res.ok) {
        return Promise.reject()
    }
    return res;
}
Copy after login

The goal is to reject the promise and catch the error in the reducer if the status code is not OK. However, the code is not working as intended: the promise is not getting rejected.

Understanding Fetch Promises

Fetch promises only reject with a TypeError when a network error occurs. Responses with 4xx or 5xx status codes are not considered network errors, so the error is not being thrown.

Throwing Custom Errors

To catch these non-network errors, we can manually throw an error if the status code indicates a failed request:

function fetchVehicle(id) {
  return fetch(`http://swapi.co/api/vehicles/${id}/`)
    .then(response => {
      if (!response.ok) {
        throw new Error('Something went wrong');
      }
      return response.json();
    })
    .catch(error => {
      console.log(error);
    });
}
Copy after login

Now, if the request returns a non-OK status code, it will trigger the error handler and log the error message. The reducer can then handle this error appropriately.

The above is the detailed content of How to Catch Errors with Fetch Promises: Why Conditional Rejection Doesn't Work?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template