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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With