在 promise.catch 之外抛出错误

Error getting thrown outside of promise.catch

我很困惑为什么这个错误(在代码中显示)会同时触发 Promise catch 和 try-catch:

async dispatch => {
    try {
      let dataUrl = await getBlob(url).catch(ex => {
        console.log(ex);   <=== This triggers
        return url;
      });
    }
    catch (err) {
      console.log(err);  <=== This triggers
    }
}

getBlob 看起来像这样:

getBlob = url =>
  fetch(url)
    .then(response => {
      if (response.ok) {
        return response.blob();
      } else {
        throw new Error("...");  <=== Error thrown
      }
    })

这是因为您的 getBlob() 函数抛出一个错误,触发了 getBlob() 的 catch

现在当那个 catch 被触发时,try/catch 块认为它正在失败并最终触发外部 catch。

你可以有这样的东西:

async dispatch => {
    try {
      let dataUrl = await getBlob(url);
    }
    catch (err) {
      console.log(err);  <=== This triggers
    }
}

外部 catch 将捕获 getBlob() 的任何错误,无需添加 catch

希望对您有所帮助。