【问题标题】:AbortController and fetch: how to distinguish network error from abort errorAbortController 和 fetch:如何区分网络错误和中止错误
【发布时间】:2020-08-27 16:27:45
【问题描述】:

所以我有一个像这样的中止控制器的获取:

async function fn() {
  const abortController = new AbortController();

  try {
    const response = await fetch(/* ... */, { signal: abortController.signal });
    // ...
  } catch (e) {
    // how can I tell if `e` is from a network error (e.g. offline)
    // or an error from an abort
  }
}

如何判断e 是网络错误还是中止错误?

【问题讨论】:

    标签: javascript fetch-api


    【解决方案1】:
    abortController.signal.aborted
    

    会告诉你AbortSignal 是否被解雇。

    https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/aborted

    或者,如果错误 name 属性是 'AbortError'

    e.name === 'AbortError'
    

    您可以单独从错误中检测,但要注意:

    Current version of Firefox rejects the promise with a DOMException

    因此,检查abortController.signal.aborted 似乎是最安全的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-14
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      相关资源
      最近更新 更多