即使response.ok为false,Fetch Api.then函数也会运行



我正试图使用提取api 从本地网络提取资源

获取后,我想检查响应类型并采取相应的

但是,当我收到500的状态并试图返回错误回调时,本应仅在response.okfalse时运行的.then()函数会双向运行

fetch(testUrl, { headers, method: "POST" })
.then(response => {
if (response.status === 200) { return response.json() }
if (response.status === 401) { Logout() }
if (response.status === 500) {
return setTestApiFetchError({
'error_type': "SERVER_ERROR",
"error": true
})
}
})
.then(data => console.log(Data))

函数.then(data => console.log(data))与无关地运行

这里有几个链接可能会有所帮助:如何使用then((将Fetch响应的JSON主体传递给Throw Error((?https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetchhttps://usefulangle.com/post/314/javascript-fetch-error-handling

正如Ali所提到的,你可能想拒绝或抛出500的响应,让它进入一个捕获块。就我个人而言,我只需检查response.ok,然后处理catch中的任何错误:

fetch(testUrl, { headers, method: "POST" })
.then((response,reject)=> {
if (response.ok) return response.json();
return Promise.reject(rejectReponse)
})
.then(success)
.catch(fail)

或者,如果您能够使用async/await:

try{
const response = await fetch(testUrl, { headers, method: "POST" });
if (!response.ok) throw response;
//response is 200-209
const data = await response.json();
//etc.
}catch(e){
if (e.status === 401) logout();
//handle server/client errors
}

您需要使用决心和拒绝参数来处理您的承诺

试试这个

const tt =  fetch(testUrl, { headers, method: "POST" })
.then((response,reject)=> {
const rejectReponse= {
"error_type": "SERVER_ERROR",
"error": true
}
if (response.ok === true) return response.json() 
else if (response.status===500) return  reject (rejectReponse)
})

tt.then(x=>console.log(x)).then(undefined,x=>console.log(x))

要在本文中了解更多支票承诺:https://learnjsx.com/category/2/posts/es6-promise

最新更新