Rico Kahler
Rico Kahler

Reputation: 19202

AbortController and fetch: how to distinguish network error from abort error

So I have a fetch with an abort controller like so:

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?

Upvotes: 27

Views: 11398

Answers (1)

spender
spender

Reputation: 120380

abortController.signal.aborted

will tell you if the AbortSignal fired.

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

Alternatively if the error name prop is 'AbortError'

e.name === 'AbortError'

you can detect from the error alone, but beware:

Current version of Firefox rejects the promise with a DOMException

Therefore, checking abortController.signal.aborted seems like the safest.

Upvotes: 39

Related Questions