简体   繁体   English

AbortController 和 fetch:如何区分网络错误和中止错误

[英]AbortController and fetch: how to distinguish network error from abort error

So I have a fetch with an abort controller like so:所以我有一个中止 controller 的获取,如下所示:

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
  }
}

How can I tell if e is a.network error or an abort error?我如何判断e是网络错误还是中止错误?

abortController.signal.aborted

will tell you if the AbortSignal fired.会告诉您AbortSignal触发。

See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/aborted请参阅https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/aborted

Alternatively if the error name prop is 'AbortError'或者,如果错误name prop 是'AbortError'

e.name === 'AbortError'

you can detect from the error alone, but beware:您可以单独从错误中检测到,但要注意:

Current version of Firefox rejects the promise with a DOMException当前版本的 Firefox 拒绝带有 DOMException 的 promise

Therefore, checking abortController.signal.aborted seems like the safest.因此,检查abortController.signal.aborted似乎是最安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM