Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Throw original error on network error #78

Merged
merged 1 commit into from
Jun 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,11 @@ async function axiosFetch (
try {
result = await axios.request(config);
} catch (err) {
result = err.response;
if (err.response) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Without this change the original error is masked by a new error: TypeError: Cannot read property 'headers' of undefined.. This is because the code below assumes that response is defined and attempts to read attributes from it.

result = err.response;
} else {
throw err;
}
}

const fetchHeaders = new FetchHeaders(result.headers);
Expand Down
10 changes: 9 additions & 1 deletion test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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`;
Expand Down