From 505e3d17343064647b91cd964d31443dca624bf2 Mon Sep 17 00:00:00 2001 From: Gus Narea Date: Sat, 20 Jun 2020 20:01:04 +0100 Subject: [PATCH] feat: Include reason why request is denied in exception message --- src/lib/client.spec.ts | 11 +++++++++++ src/lib/client.ts | 7 +++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/lib/client.spec.ts b/src/lib/client.spec.ts index 7103281..1f9414c 100644 --- a/src/lib/client.spec.ts +++ b/src/lib/client.spec.ts @@ -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}`), + ); + }); }); diff --git a/src/lib/client.ts b/src/lib/client.ts index d91c8b6..c55cfda 100644 --- a/src/lib/client.ts +++ b/src/lib/client.ts @@ -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; }