From 1ed7e2ab2b3cc1df6d805dd4327dd7a1fdddd69e Mon Sep 17 00:00:00 2001 From: wattroll Date: Fri, 29 Dec 2023 21:06:14 +0200 Subject: [PATCH] fix: provide statusText as error message on retryable network errors Previously responses that indicate retryable network errors (e.g. proxy errors) resulted into `AuthRetryableFetchError` with dreaded `"{}"` as an `Error#message`. This commit provides `Response.statusText` as an error message in those cases. --- src/lib/fetch.ts | 2 +- test/fetch.test.ts | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/lib/fetch.ts b/src/lib/fetch.ts index 3bc4ef57..f0d74668 100644 --- a/src/lib/fetch.ts +++ b/src/lib/fetch.ts @@ -42,7 +42,7 @@ async function handleError(error: unknown) { if (NETWORK_ERROR_CODES.includes(error.status)) { // status in 500...599 range - server had an error, request might be retryed. - throw new AuthRetryableFetchError(_getErrorMessage(error), error.status) + throw new AuthRetryableFetchError(error.statusText, error.status) } let data: any diff --git a/test/fetch.test.ts b/test/fetch.test.ts index 394c2299..ba2e0983 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -105,6 +105,26 @@ describe('fetch', () => { await server.start() }) + test('should throw AuthRetryableFetchError when response is a network error', async () => { + const route = server + .get('/') + .mockImplementationOnce((ctx) => { + ctx.status = 504 + ctx.statusText = 'Gateway Timeout' + ctx.body = 'Gateway Timeout' + }) + .mockImplementation((ctx) => { + ctx.status = 200 + }) + + const url = server.getURL().toString() + const result = _request(fetch, 'GET', url) + await expect(result).rejects.toBeInstanceOf(AuthRetryableFetchError) + await expect(result).rejects.toMatchObject({ status: 504, message: 'Gateway Timeout' }) + + expect(route).toHaveBeenCalledTimes(1) + }) + test('should work with custom fetch implementation', async () => { const customFetch = (async () => { return {