Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

catch error in fall back to utf8 #2336

Merged
merged 3 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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