考虑下面的代码,当来自web端点的答复是"200-ish“(2xx和类似的)时,它应该做一些事情,而当答复是404时(但是对于非-404,并管理网络问题)。
fetch('https://httpstat.us/404')
.then((r) => {
if (r.ok) {
console.log(`response 200-ish`)
return r // go to the next .then()
} else {
console.log(`response is not 200-ish`)
return Promise.reject(r.status) // the chain for then() breaks here
}
})
.then((r) => {
console.log('do stuff for 200-ish')
})
.catch((err) => {
if (err === 404) {
console.log('do 404 stuff')
} else {
console.log('do stuff because of another response from the API')
}
// how to address network problems??
})
如果我取chance
https://httpstat.us/404代码是OK
https://httpstat.us/500 (既不是200也不是404,而是来自API服务器的正确答复),代码是OK< code >E 110由I提取< code >D14 (=不正确的URL,产生网络错误),代码不是OKH 215/code>F 216换句话说,最后一个else捕获没有显式检查的任何内容。
如何区分显式中断与承诺链(公开返回代码)和网络错误?
发布于 2022-06-10 11:30:13
你需要一条轻巧复杂的承诺链:
let fetchPromise = fetch('https://httpstat.us/404');
fetchPromise.catch((e) => {
// Do stuff only for network errors
});
fetchPromise.then((r) => {
if (r.ok) {
return r.json().then(
/* The JSON here is just a example if you need to wrap more promises */
/* Do something with a 200 */
)
} else {
/* Do something with non-200 ish */
}
})另一种选择是:
try:
let response = await fetch('...');
catch (ex) {
/* do something with network errors */
}
if (!response.ok) {
/* do something with non-network errors */
throw new Error()
}
/* do something with 200 */https://stackoverflow.com/questions/72573400
复制相似问题