Home >Web Front-end >JS Tutorial >How Can I Manually Reject Fetch Promises Based on HTTP Status Codes?
Fetch: Controlling Promise Rejection Based on HTTP Status Code
In the realm of fetch, promises are typically only rejected when encountering network errors. However, in scenarios where 4xx or 5xx HTTP status codes are returned, the promise isn't rejected by default.
Problem:
In your provided code, you're attempting to intercept and reject the promise when the HTTP response status indicates an error. However, the promise is not getting rejected as expected.
Reason:
Fetch promises only reject with a TypeError when a network error occurs. Since 4xx and 5xx responses aren't network errors, there's nothing to catch. To reject the promise manually, you'll need to throw an error yourself.
Solution:
To resolve this issue and reject the promise based on HTTP status, you can modify your code as follows:
import 'whatwg-fetch'; function fetchVehicle(id) { return dispatch => { return dispatch({ type: 'FETCH_VEHICLE', payload: fetch(`http://swapi.co/api/vehicles/${id}/`) .then(res => { if (!res.ok) { const error = new Error('HTTP Error: ' + res.status); throw error; // Throwing the error here will cause fetch to reject the promise } return res; }) .then(res => res.json()) .catch(error => { throw error; }) }); }; }
By introducing the error handling logic within the fetch promise, you can now reject the promise manually if the HTTP response status indicates a non-success condition. This allows you to capture and handle the error appropriately in the catch block of your redux middleware.
The above is the detailed content of How Can I Manually Reject Fetch Promises Based on HTTP Status Codes?. For more information, please follow other related articles on the PHP Chinese website!