diff --git a/source/as-promise/index.ts b/source/as-promise/index.ts index eee8903da..35d2bff63 100644 --- a/source/as-promise/index.ts +++ b/source/as-promise/index.ts @@ -7,7 +7,7 @@ import { type RequestError, } from '../core/errors.js'; import Request from '../core/index.js'; -import {parseBody, isResponseOk, type Response} from '../core/response.js'; +import {parseBody, isResponseOk, type Response, ParseError} from '../core/response.js'; import proxyEvents from '../core/utils/proxy-events.js'; import type Options from '../core/options.js'; import {CancelError, type CancelableRequest} from './types.js'; @@ -62,7 +62,12 @@ export default function asPromise(firstRequest?: Request): CancelableRequest< response.body = parseBody(response, options.responseType, options.parseJson, options.encoding); } catch (error: any) { // Fall back to `utf8` - response.body = response.rawBody.toString(); + try { + response.body = response.rawBody.toString(); + } catch (error) { + request._beforeError(new ParseError(error as Error, response)); + return; + } if (isResponseOk(response)) { request._beforeError(error); diff --git a/test/error.ts b/test/error.ts index 273e08308..1360733c2 100644 --- a/test/error.ts +++ b/test/error.ts @@ -343,6 +343,23 @@ test('no uncaught parse errors #2', async t => { await close(); }); +test('no uncaught parse errors on fallback to utf8', withServer, async (t, server, got) => { + server.get('/', (_request, response) => { + const buffer = Buffer.alloc(536_870_912, 'A'); + response.statusCode = 200; + response.end(buffer); + }); + + await t.throwsAsync(got({ + timeout: { + request: 60_000, + }, + }), { + instanceOf: RequestError, + code: 'ERR_BODY_PARSE_FAILURE', + }); +}); + // Fails randomly on Node 10: // Blocked by https://github.com/istanbuljs/nyc/issues/619 // eslint-disable-next-line ava/no-skip-test