gpt4 book ai didi

reactjs - 当 API 返回任何错误时,catch block 不会被触发

转载 作者:行者123 更新时间:2023-12-05 04:44:33 26 4
gpt4 key购买 nike

我正在进行一个普通的 API 调用,但出于某种原因,我没有在我的 catch block 中看到 console.log(err)当我收到 500 错误时。它总是在我的 then block 中触发 console.log(result)我做错了什么?

const startHandler = () => {
setOpenLoadingModal(true);
fetch(url, {
method: 'post',
body: JSON.stringify(payload),
headers: headers,
})
.then((response) => response.json())
.then((result) => {
console.log("🚀 ~ file: index.js ~ line 159 ~ .then ~ result", result)
const { client_id, token } = result;
if (!token || !client_id){
setOpenErrorModal(true);
return setOpenLoadingModal(false);
} else{
return history.push({
pathname: FORMS_URL.LANDING_PAGE,
});
})
.catch((err) => {
console.log(err)

setOpenErrorModal(true);
setOpenLoadingModal(false);
});
};

最佳答案

fetch 不拒绝 4xx/5xx 错误状态

Using Fetch

The Promise returned from fetch() won’t reject on HTTP error statuseven if the response is an HTTP 404 or 500. Instead, as soon as theserver responds with headers, the Promise will resolve normally (withthe ok property of the response set to false if the response isn’t inthe range 200–299), and it will only reject on network failure or ifanything prevented the request from completing.

Checking that the fetch was successful

您应该检查 response.ok 状态。

const startHandler = () => {
setOpenLoadingModal(true);
fetch(url, {
method: 'post',
body: JSON.stringify(payload),
headers: headers,
})
.then((response) => {
if (!response.ok) { // <-- check response OK here
throw new Error('Network response was not ok');
}
return response.json();
})
.then((result) => {
console.log("🚀 ~ file: index.js ~ line 159 ~ .then ~ result", result)
const { client_id, token } = result;
if (!token || !client_id){
setOpenErrorModal(true);
return setOpenLoadingModal(false);
} else{
return history.push({
pathname: FORMS_URL.LANDING_PAGE,
});
})
.catch((err) => {
console.log(err)

setOpenErrorModal(true);
setOpenLoadingModal(false);
});
};

关于reactjs - 当 API 返回任何错误时,catch block 不会被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69341700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com