Home > Web Front-end > JS Tutorial > body text

How to Reject a Fetch Promise and Catch Errors When the Status Code is Not OK?

DDD
Release: 2024-11-24 08:00:12
Original
840 people have browsed it

How to Reject a Fetch Promise and Catch Errors When the Status Code is Not OK?

How to Reject a Fetch Promise and Catch the Error When Status 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;
}
Copy after login

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);
});
Copy after login

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!

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