diff --git a/lib/instrumentation/http-shared.js b/lib/instrumentation/http-shared.js index 19b6afef86..5172c0e49f 100644 --- a/lib/instrumentation/http-shared.js +++ b/lib/instrumentation/http-shared.js @@ -33,9 +33,10 @@ exports.instrumentRequest = function (agent, moduleName) { ins.bindEmitter(res) endOfStream(res, function (err) { + if (trans.ended) return if (!err) return trans.end() - if (agent._conf.errorOnAbortedRequests && !trans.ended) { + if (agent._conf.errorOnAbortedRequests) { var duration = trans._timer.elapsed() if (duration > (agent._conf.abortedErrorThreshold * 1000)) { agent.captureError('Socket closed with active HTTP request (>' + agent._conf.abortedErrorThreshold + ' sec)', { @@ -47,9 +48,12 @@ exports.instrumentRequest = function (agent, moduleName) { // Handle case where res.end is called after an error occurred on the // stream (e.g. if the underlying socket was prematurely closed) - res.on('prefinish', function () { + const end = res.end + res.end = function () { + const result = end.apply(this, arguments) trans.end() - }) + return result + } }) } } diff --git a/test/instrumentation/modules/http/aborted-requests-enabled.js b/test/instrumentation/modules/http/aborted-requests-enabled.js index ae2481481b..bbad2f199e 100644 --- a/test/instrumentation/modules/http/aborted-requests-enabled.js +++ b/test/instrumentation/modules/http/aborted-requests-enabled.js @@ -37,12 +37,13 @@ test('client-side abort below error threshold - call end', { timeout: 10000 }, f var server = http.createServer(function (req, res) { setTimeout(function () { clientReq.abort() - setTimeout(function () { - res.write('Hello') // server emits clientError if written in same tick as abort + res.write('sync write') + process.nextTick(function () { + res.write('nextTick write') setTimeout(function () { - res.end(' World') + res.end('setTimeout write') }, 10) - }, 10) + }) }, (agent._conf.abortedErrorThreshold * 1000) / 2) })