diff --git a/source/core/index.ts b/source/core/index.ts index ac8078db6..a65b6dc6e 100644 --- a/source/core/index.ts +++ b/source/core/index.ts @@ -330,7 +330,10 @@ export default class Request extends Duplex implements RequestEvents { 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!); diff --git a/test/error.ts b/test/error.ts index 4073185fa..bc0039933 100644 --- a/test/error.ts +++ b/test/error.ts @@ -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