Fetch API error handling

前端 未结 3 719
借酒劲吻你
借酒劲吻你 2021-02-15 15:52

I want to display error message from my API, problem is that I can\'t reach that error if I check for response.ok, it returns Fetch error, not the one from API..

3条回答
  •  借酒劲吻你
    2021-02-15 16:16

    With the following solution one can handle JSON API error, Generic API error and Generic fetch error

    fetch("api/v1/demo", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            "data": "demo"
        })
    })
        .then(response => {
            if (!response.ok) {
                return Promise.reject(response);
            }
            return response.json();
        })
        .then(data => {
            console.log("Success");
            console.log(data);
        })
        .catch(error => {
            if (typeof error.json === "function") {
                error.json().then(jsonError => {
                    console.log("Json error from API");
                    console.log(jsonError);
                }).catch(genericError => {
                    console.log("Generic error from API");
                    console.log(error.statusText);
                });
            } else {
                console.log("Fetch error");
                console.log(error);
            }
        });
    

提交回复
热议问题