Home > Article > Web Front-end > How to Reject a Fetch Promise and Catch Errors When the Status Code is Not OK?
Many modern JavaScript applications use the Fetch API to make HTTP requests. The Fetch API returns a Promise object that resolves to a Response object. The Response object can be used to access the status code, headers, and body of the response.
Sometimes, a server will respond with a HTTP status code that indicates an error. For example, a server might respond with a 404 status code if a requested resource is not found. By default, a Fetch Promise will not reject when the server responds with a non-2xx status code.
This can make it difficult to handle errors in your code. To fix this issue, you can use the status() function to check the status code of the Response object before resolving or rejecting the Promise. Here's an example of how you can use the status() function to reject a Fetch Promise when the status code is not OK:
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; }
This code will reject the Fetch Promise if the status code of the Response object is not OK. You can then use the .catch() method to handle the error.
Here's an example of how you can use the .catch() method to handle the error:
fetchVehicle(1).catch(error => { console.log(error); });
This code will log the error to the console.
The above is the detailed content of How to Reject a Fetch Promise and Catch Errors When the Status Code is Not OK?. For more information, please follow other related articles on the PHP Chinese website!