如果API调用未返回200,但我试图提高errorBoundary,但是在调用API调用时catch块中立即调用了raiseErrorBoundary,我怎么做才能使它仅在出现错误时才被调用被扔了吗?
export const downgradeAPICall = (raiseErrorBoundary) => {
return fetch('http://localhost:42005/Upgrade/Downgrade', {
method: 'POST'
}).then(res => {
if(res.status != 200){
throw new Error("An error has occured during API request!")
} else {
window.location.reload()
}
})
.catch((error)=>{
console.log(error)
raiseErrorBoundary()
})
}
答案 0 :(得分:1)
200
是“ OK”状态响应。现在,如果成功,您将引发一个错误,因此无论您以何种方式编写它,都可能会引发一个错误。相反,您可能想要if(res.status !== 200)
(也将“出现”拼写为“出现”)
export const downgradeAPICall = (raiseErrorBoundary) => {
return fetch('http://localhost:42005/Upgrade/Downgrade', {
method: 'POST'
}).then(res => {
if(res.status !== 200){
throw new Error("An error has occurred during API request!")
} else {
window.location.reload()
}
})
.catch((error)=>{
console.log(error)
raiseErrorBoundary()
})
}