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', () => {