Skip to content

Commit

Permalink
fix(redux-requests-fetch): fix handling of request abortion with nati…
Browse files Browse the repository at this point in the history
…ve `AbortController`

Add `isNativeAbortError` guard function & tests
Rethrow `'REQUEST_ABORTED'` when a native `AbortError` is emitted
  • Loading branch information
medfreeman authored and klis87 committed Nov 13, 2021
1 parent 455a95a commit 7002613
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
8 changes: 8 additions & 0 deletions packages/redux-requests-fetch/src/fetch-api-driver.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import isAbsoluteUrl from 'axios/lib/helpers/isAbsoluteURL';

import { isNativeAbortError } from './helpers';

const responseTypes = ['arraybuffer', 'blob', 'formData', 'json', 'text', null];

const getData = (response, responseType) => {
Expand Down Expand Up @@ -50,6 +52,12 @@ export const createDriver = (
throw response;
},
);
}).catch(error => {
if (isNativeAbortError(error)) {
throw 'REQUEST_ABORTED';
}

throw error;
});

responsePromise.cancel = () => abortSource.abort();
Expand Down
7 changes: 7 additions & 0 deletions packages/redux-requests-fetch/src/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// a real browser will throw an instance of `DomException`, polyfills an instance of `AbortError`
// https://developer.mozilla.org/en-US/docs/Web/API/AbortController#examples
// old browsers would set the exception `code` property equal to DOMException.ABORT_ERR
// https://developer.mozilla.org/en-US/docs/Web/API/DOMException/code
export const isNativeAbortError = err =>
['DOMException', 'AbortError'].includes(err.constructor.name) &&
(err.name === 'AbortError' || err.code === DOMException.ABORT_ERR);
18 changes: 18 additions & 0 deletions packages/redux-requests-fetch/src/helpers.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { isNativeAbortError } from './helpers';

describe('helpers', () => {
describe('isNativeAbortError', () => {

it('properly identifies a native `AbortError`', () => {
expect(isNativeAbortError(new DOMException('request aborted', 'AbortError'))).toBe(true);
});

it('does not identify another Error', () => {
expect(isNativeAbortError(new Error())).toBe(false);
});

it('does not identify a string', () => {
expect(isNativeAbortError('REQUEST_ABORTED')).toBe(false);
});
});
});

0 comments on commit 7002613

Please sign in to comment.