Skip to content

Commit

Permalink
Prevent uncaught ParseErrors on initial successful response
Browse files Browse the repository at this point in the history
Fixes #1527
  • Loading branch information
szmarczak committed Apr 13, 2021
1 parent f455c7c commit 77df9c3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
5 changes: 4 additions & 1 deletion source/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,10 @@ export default class Request extends Duplex implements RequestEvents<Request> {
const typedError = error as RequestError;

void (async () => {
if (response && !response.rawBody) {
// Node.js parser is really weird.
// It emits post-request Parse Errors on the same instance as previous request. WTF.
// Therefore we need to check if it has been destroyed as well.
if (response && !response.rawBody && !this._request?.destroyed) {
// @types/node has incorrect typings. `setEncoding` accepts `null` as well.
response.setEncoding(this.readableEncoding!);

Expand Down
25 changes: 25 additions & 0 deletions test/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,31 @@ test('no uncaught parse errors', async t => {
await close();
});

test('no uncaught parse errors #2', async t => {
const server = net.createServer();

const listen = promisify(server.listen.bind(server));
const close = promisify(server.close.bind(server));

await listen();

server.on('connection', socket => {
socket.resume();
socket.write([
'HTTP/1.1 200 OK',
'content-length: 1',
'',
'0a'
].join('\r\n'));
});

await t.throwsAsync(got(`http://localhost:${(server.address() as net.AddressInfo).port}`), {
message: /^Parse Error/
});

await close();
});

// 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 77df9c3

Please sign in to comment.