Skip to content

Commit

Permalink
Fix error handling when UTF8 decoding fails (#2336)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
archvlad and sindresorhus authored Mar 7, 2024
1 parent 897f385 commit c81a611
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
9 changes: 7 additions & 2 deletions source/as-promise/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -62,7 +62,12 @@ export default function asPromise<T>(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);
Expand Down
17 changes: 17 additions & 0 deletions test/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit c81a611

Please sign in to comment.