Home > Article > Web Front-end > 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; }
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); }); }
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!