diff --git a/lib/server.js b/lib/server.js index a5c9fbb19..245937c19 100644 --- a/lib/server.js +++ b/lib/server.js @@ -890,7 +890,9 @@ Server.prototype._routeErrorResponse = function _routeErrorResponse( null, err, function _emitErrorEvents() { - res.send(err); + if (!res.headersSent) { + res.send(err); + } return self._finishReqResCycle(req, res, null, err); } ); diff --git a/test/server.test.js b/test/server.test.js index 436906a78..7e3009e7b 100644 --- a/test/server.test.js +++ b/test/server.test.js @@ -224,6 +224,31 @@ test('rm route and clear cached route', function(t) { }); }); +test('_routeErrorResponse does not cause uncaughtException when called when header has already been sent', function( + t +) { + SERVER.on('MethodNotAllowed', function(req, res, error, next) { + res.json(405, { status: 'MethodNotAllowed' }); + try { + next(); + } catch (err) { + t.fail( + 'next() should not throw error when header has already been sent' + ); + } + t.end(); + }); + + SERVER.post('/routePostOnly', function tester(req, res, next) { + next(); + }); + + CLIENT.get('/routePostOnly', function(err, _, res) { + t.ok(err); + t.equal(res.statusCode, 405); + }); +}); + test('GH-1171: rm one version of the routes, other versions should still work', function( t ) {