From 035d9dd833c3ad63148bc50facaee421f4792192 Mon Sep 17 00:00:00 2001 From: Daniel Bankhead Date: Wed, 6 Sep 2023 18:26:57 -0700 Subject: [PATCH] fix: don't throw an error within a `GaxiosError` (#569) --- src/common.ts | 11 +++++++++-- test/test.getch.ts | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/common.ts b/src/common.ts index 2dbc7e2d..edee0efd 100644 --- a/src/common.ts +++ b/src/common.ts @@ -43,7 +43,14 @@ export class GaxiosError extends Error { super(message); if (this.response) { - this.response.data = translateData(config.responseType, response?.data); + try { + this.response.data = translateData(config.responseType, response?.data); + } catch { + // best effort - don't throw an error within an error + // we could set `this.response.config.responseType = 'unknown'`, but + // that would mutate future calls with this config object. + } + this.status = this.response.status; } @@ -357,7 +364,7 @@ export function defaultErrorRedactor(data: { data.config.url = url.toString(); } catch { - // ignore error + // ignore error - no need to parse an invalid URL } } diff --git a/test/test.getch.ts b/test/test.getch.ts index 15d2ba48..844cba04 100644 --- a/test/test.getch.ts +++ b/test/test.getch.ts @@ -98,6 +98,27 @@ describe('🚙 error handling', () => { } ); }); + + it('should not throw an error during a translation error', () => { + const notJSON = '.'; + const response: GaxiosResponse = { + config: { + responseType: 'json', + }, + data: notJSON, + status: 500, + statusText: '', + headers: {}, + request: { + responseURL: url, + }, + }; + + const error = new GaxiosError('translation test', {}, response); + + assert(error.response, undefined); + assert.equal(error.response.data, notJSON); + }); }); describe('🥁 configuration options', () => {