首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何区分网络错误和故意中断?

如何区分网络错误和故意中断?
EN

Stack Overflow用户
提问于 2022-06-10 11:16:00
回答 1查看 27关注 0票数 1

考虑下面的代码,当来自web端点的答复是"200-ish“(2xx和类似的)时,它应该做一些事情,而当答复是404时(但是对于非-404,并管理网络问题)。

代码语言:javascript
复制
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

  • if的代码是OK

  • (如果我获取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捕获没有显式检查的任何内容。

如何区分显式中断与承诺链(公开返回代码)和网络错误?

EN

回答 1

Stack Overflow用户

发布于 2022-06-10 11:30:13

你需要一条轻巧复杂的承诺链:

代码语言:javascript
复制
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 */
    }
  })

另一种选择是:

代码语言:javascript
复制
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 */
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72573400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档