捕获获取错误

新手上路,请多包涵

我的理解是,一段在调用堆栈中任何地方抛出错误的代码都可以在最终的 catch 块中被捕获。对于获取错误,当没有互联网可用时,当我在 callCallAPI 中创建 APIwithoutCatch 时,未捕获到错误。而 APIwithCatch 捕获自己的错误。所有其他错误,例如 404,都在我想要的任何地方都被捕获。

 async function APIwithcatch() {
  try {
    var response = await fetch("http://wwww.dfdfdf.com/user.json");
    return response;
  } catch (e) {
    console.log(e);
  }
}

async function APIwithoutcatch() {
  var response = await fetch("http://wwww.dfdfdf.com/user.json");
  return response;
}

function callCallAPI() {
  try {
    // return APIwithcatch();
    return APIwithoutcatch();
  } catch (e) {
    console.log(e);
  }
}
callCallAPI();

我假设任何错误都应该流向调用堆栈是否正确? net::ERR_INTERNET_DISCONNECTED 错误有什么特别之处?

原文由 DrEarnest 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 588
2 个回答

APIwithoutcatch 是一个 async function 它不会抛出异常但会拒绝它返回的承诺。 You need to wait for the promise, either with then or await syntax (just like you did await the fetch within APIwithcatch ):

 async function API() {
  return fetch("http://wwww.example.com/user.json");
}

function callAPI() {
  try {
    await API();
  } catch (e) {
    console.log(e);
  }
}
callAPI();

原文由 Bergi 发布,翻译遵循 CC BY-SA 4.0 许可协议

根据 MDN, fetch() API 仅在“遇到网络错误时拒绝承诺,尽管这通常意味着权限问题或类似问题。”基本上 fetch() 只会在用户离线时拒绝承诺,或者发生一些不太可能的网络错误,例如 DNS 查找失败。

然而,fetch 提供了一个 ok 标志,我们可以使用它来检查 HTTP 状态代码是否成功以及 throw 用户定义的异常

await response.json() 将从响应中提取 JSON 正文内容,以便我们可以 throw 将其添加到 .catch 块。

     async function APIwithcatch() {
      try {
        var response = await fetch("http://wwww.dfdfdf.com/user.json");

        if (!response.ok) throw await response.json();

        return response;

      } catch (e) {
        console.log(e);
      }
    }

原文由 Pecata 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题