diff --git a/lib/server.js b/lib/server.js index 0b81f4424..4cec6130e 100644 --- a/lib/server.js +++ b/lib/server.js @@ -1258,8 +1258,14 @@ Server.prototype._finishReqResCycle = function _finishReqResCycle( // after event has signature of function(req, res, route, err) {...} self.emit('after', req, res, route, err || res.err); } else { - // preserve error for actual finish - res.err = err; + // Store error for when the response is flushed and we actually emit the + // 'after' event. The "err" object passed to this method takes + // precedence, but in case it's not set, "res.err" may have been already + // set by another code path and we want to preserve it. The caveat thus + // is that the 'after' event will be emitted with the latest error that + // was set before the response is fully flushed. While not ideal, this + // is on purpose and accepted as a reasonable trade-off for now. + res.err = err || res.err; } };