Skip to content

Commit

Permalink
feat: Include reason why request is denied in exception message
Browse files Browse the repository at this point in the history
  • Loading branch information
gnarea committed Jun 20, 2020
1 parent 202a6bf commit 505e3d1
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
11 changes: 11 additions & 0 deletions src/lib/client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,4 +259,15 @@ describe('deliverParcel', () => {
const expectedError = new PoHTTPError(axiosError, 'Failed to deliver parcel');
await expectPromiseToReject(deliverParcel(url, body), expectedError);
});

test('HTTP 4XX errors should mention the reason if available', async () => {
// @ts-ignore
stubAxiosPost.mockReset();
const reason = 'Denied';
stubAxiosPost.mockRejectedValueOnce({ response: { data: { message: reason }, status: 400 } });

await expect(deliverParcel(url, body)).rejects.toEqual(
new PoHTTPError(`Failed to deliver parcel: ${reason}`),
);
});
});
7 changes: 5 additions & 2 deletions src/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,17 @@ async function postRequest(
});
} catch (error) {
const responseStatus = error.response?.status;
const reason = error.response?.data?.message;
if (responseStatus && responseStatus === 403) {
const reason = error.response?.data?.message;
throw new PoHTTPInvalidParcelError(
reason ? `Server refused to accept parcel: ${reason}` : 'Server refused to accept parcel',
);
}
if (!responseStatus || responseStatus < 300 || 400 <= responseStatus) {
throw new PoHTTPError(error, 'Failed to deliver parcel');
throw new PoHTTPError(
error,
reason ? `Failed to deliver parcel: ${reason}` : 'Failed to deliver parcel',
);
}
response = error.response;
}
Expand Down

0 comments on commit 505e3d1

Please sign in to comment.