From 098e71a71b4508a327b325efb55c9e9117457371 Mon Sep 17 00:00:00 2001 From: Wes Todd Date: Sun, 1 Sep 2024 09:13:46 -0500 Subject: [PATCH] fix: gracefully handle when handling an error and socket is null --- HISTORY.md | 5 +++++ index.js | 4 +++- test/test.js | 21 +++++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/HISTORY.md b/HISTORY.md index ec2d38b..6222ddb 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,3 +1,8 @@ +unreleased +================== + + * Gracefully handle when handling an error and socket is null + 1.2.0 / 2022-03-22 ================== diff --git a/index.js b/index.js index f628e42..ea16fd2 100644 --- a/index.js +++ b/index.js @@ -125,7 +125,9 @@ function finalhandler (req, res, options) { // cannot actually respond if (headersSent(res)) { debug('cannot %d after headers sent', status) - req.socket.destroy() + if (req.socket) { + req.socket.destroy() + } return } diff --git a/test/test.js b/test/test.js index 0b5d15c..8e78aa5 100644 --- a/test/test.js +++ b/test/test.js @@ -571,4 +571,25 @@ describe('finalhandler(req, res)', function () { }) }) }) + + if (parseInt(process.version.split('.')[0].replace(/^v/, ''), 10) > 11) { + describe('req.socket', function () { + it('should not throw when socket is null', function (done) { + request(createServer(function (req, res, next) { + res.statusCode = 200 + res.end('ok') + process.nextTick(function () { + req.socket = null + next(new Error()) + }) + })) + .get('/') + .end(function () { + assert.strictEqual(this.res.statusCode, 200) + assert.strictEqual(this.res.text, 'ok') + done() + }) + }) + }) + } })