From 7236f650f6b6d4126f98fa1a9f64620d89f0421d Mon Sep 17 00:00:00 2001 From: Jeff Jagoda Date: Tue, 29 Jun 2021 08:45:03 -0400 Subject: [PATCH] Throw original error on network error Axios errors do not contain a `response` attribute when there is no response (ex. network errors). --- src/index.ts | 6 +++++- test/index.test.ts | 10 +++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/index.ts b/src/index.ts index d00fe2f..b6bbf79 100644 --- a/src/index.ts +++ b/src/index.ts @@ -55,7 +55,11 @@ async function axiosFetch ( try { result = await axios.request(config); } catch (err) { - result = err.response; + if (err.response) { + result = err.response; + } else { + throw err; + } } const fetchHeaders = new FetchHeaders(result.headers); diff --git a/test/index.test.ts b/test/index.test.ts index cfa596f..3e283ff 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -45,7 +45,9 @@ test.before(() => { .get('/failure') .reply(501) .get('/failureBody') - .reply(400, { test: true }); + .reply(400, { test: true }) + .get('/error') + .replyWithError('simulated failure'); }); async function dualFetch (input: string, init?: FetchInit) { @@ -199,6 +201,12 @@ test('returns the expected response body on a failure', async (test) => { test.deepEqual(axiosResponse.headers, expectedResponse.headers); }); +test('throws the original error on a network error', async (test) => { + const axiosFetch = buildAxiosFetch(axios); + const error = await test.throwsAsync(axiosFetch(`${TEST_URL_ROOT}/error`)); + test.is(error.message, 'simulated failure'); +}); + test('allows transforming request options', async (test) => { const originalUrl = `${TEST_URL_ROOT}/success/text`; const transformedUrl = `${TEST_URL_ROOT}/success/json`;