Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 840
Rico Kahler Avatar asked May 11 '20 23:05

Rico Kahler


People also ask

How do I use fetch controller for abortion?

When the fetch request is initiated, we pass in the AbortSignal as an option inside the request's options object (the {signal} below). This associates the signal and controller with the fetch request and allows us to abort it by calling AbortController. abort() , as seen below in the second event listener.

What is abort signal?

The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a fetch request) and abort it if required via an AbortController object. EventTarget AbortSignal.

What is abort controller in react JS?

The abort() method of the AbortController interface aborts a DOM request before it has completed. This is able to abort fetch requests, the consumption of any response bodies, or streams.


Video Answer


1 Answers

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.

like image 74
spender Avatar answered Oct 19 '22 02:10

spender