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; }