2 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
僅當(dāng)無法發(fā)出請求時(shí),F(xiàn)etch API 才會(huì)失敗。如果可以,即使?fàn)顟B(tài)不好,fetch 也會(huì)成功執(zhí)行。
因?yàn)閠hrow new Error(err)從未被調(diào)用過,所以當(dāng)您嘗試將 a 解析invalid string content為 json 對象 ( res.json())時(shí),它只會(huì)被調(diào)用。我來賓,在 401 情況下,您的服務(wù)器返回一個(gè)有效的 json 字符串,例如{message: "Unauthorized"},然后res.json()工作正常,并且沒有拋出任何錯(cuò)誤。
如果你想捕捉 http 錯(cuò)誤,那么http status codeof resobject 是一個(gè)正確的方法:
return await fetch(url, options)
.then(res => {
if (res.status >= 300) { // error http status code range
throw new Error(res.status) // throw a error to the catch block
}
return res.json();
})
.catch(err => {
throw new Error(err) // catch and throw to the error of previous `.then` block
})
然后再試一次。

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
這就是我的工作:
return fetch(url, options)
.then(async res => {
if (!res.ok) {
const err = await res.json()
throw err.message || res.statusText
}
return res.json()
})
.catch(err => {
throw new Error(err)
})
你可以這樣稱呼它:
const response = await myFetch('/forgot', {
}, {
headers: {
'x-contact': 'hello@puump.com'
}
}).catch(err => {
msg = err.message;
return;
});
if (response) {
push('/');
}
添加回答
舉報(bào)