From 15de2a520f1a15e46736c5b5282433286ad42247 Mon Sep 17 00:00:00 2001 From: Gar Date: Mon, 22 Aug 2022 07:25:14 -0700 Subject: [PATCH] fix(json): don't catch body errors The thrown error this suffices, we only catch parse errors --- lib/body.js | 2 +- test/body.js | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/body.js b/lib/body.js index 5889330..9d1b45d 100644 --- a/lib/body.js +++ b/lib/body.js @@ -72,8 +72,8 @@ class Body { } async json () { + const buf = await this[CONSUME_BODY]() try { - const buf = await this[CONSUME_BODY]() return JSON.parse(buf.toString()) } catch (er) { throw new FetchError( diff --git a/test/body.js b/test/body.js index 1d280e9..0dfae69 100644 --- a/test/body.js +++ b/test/body.js @@ -253,7 +253,7 @@ t.test('more static method coverage', async t => { t.equal(Body.getTotalBytes({ body: {} }), null) }) -t.test('json', async t => { +t.test('json FetchError', async t => { t.same(await new Body('{"a":1}').json(), { a: 1 }) await t.rejects(Object.assign(new Body('a=1'), { url: 'asdf' }).json(), { name: 'FetchError', @@ -263,6 +263,18 @@ t.test('json', async t => { }) }) +t.test('json body error', async t => { + const s = new PassThrough() + const b = new Body(s) + b.url = 'xyz' + setTimeout(() => s.emit('error', new RangeError('hello'))) + await t.rejects(b.json(), { + name: 'FetchError', + message: 'Could not create Buffer from response body for xyz: hello', + type: 'system', + }) +}) + t.test('handles environments where setTimeout does not have unref', async t => { const originalSetTimeout = setTimeout // simulate environments without unref()