代码之家  ›  专栏  ›  技术社区  ›  DrEarnest

捕获获取错误

  •  1
  • DrEarnest  · 技术社区  · 7 年前

    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();
    我假设任何错误都应该向下流调用堆栈是正确的还是错误的?
    2 回复  |  直到 7 年前
        1
  •  2
  •   Bergi    7 年前

    APIwithoutcatch 是一个 async function -它不会抛出异常,而是拒绝它返回的承诺。你需要等待承诺,或者 then await 等待 fetch 在内部 APIwithcatch ):

    async function API() {
      return fetch("http://wwww.example.com/user.json");
    }
    
    function callAPI() {
      try {
        await API();
      } catch (e) {
        console.log(e);
      }
    }
    callAPI();
    
        2
  •  0
  •   Pecata    5 年前

    Per MDN, fetch()API只在遇到网络错误时拒绝承诺,尽管这通常意味着权限问题或类似问题。基本上,fetch()只在用户脱机或发生某些不太可能的网络错误(如DNS查找失败)时拒绝承诺。

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

    await response.json() 将从响应中提取JSON正文内容,以便我们可以 .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);
          }
        }
    
        3
  •  -1
  •   Igor    7 年前

    UPD:有你的问题了,不幸的是你不能在你的代码中发现类似的错误

    回迁是异步的,所以不能使用 try {} catch {} 施工、使用 .then().catch() 相反:

    async function APIwithoutcatch() {
      var response = await fetch("http://wwww.dfdfdf.com/user.json");
      return response;
    }
    
    function callCallAPI() {
      return APIwithoutcatch()
        .then((data) => {
          console.log(data)
        })
        .catch((e) => {
          console.log(e)
        })
    }
    
    callCallAPI();
    
    推荐文章