From 957f915d428805f05187f13bc79321643431cfaa Mon Sep 17 00:00:00 2001 From: Alex Kocharin Date: Fri, 11 Oct 2013 13:49:00 +0400 Subject: [PATCH] fixing a next(err) function called twice --- lib/index.js | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/lib/index.js b/lib/index.js index deabb9e1b..44bb3307d 100644 --- a/lib/index.js +++ b/lib/index.js @@ -35,6 +35,28 @@ module.exports = function(config_hash) { }; var app = express(); + + app.use(function(req, res, next) { + var calls = 0; + res.report_error = function(err) { + calls++; + if (err.status && err.status >= 400 && err.status < 600) { + if (calls == 1) { + res.status(err.status); + res.send({error: err.msg || err.message || 'unknown error'}); + } + } else { + console.log(err); + console.log(err.stack); + if (calls == 1) { + res.status(500); + res.send({error: 'internal server error'}); + } + } + } + next(); + }); + app.use(Middleware.log_and_etagify); app.use(basic_auth(function(user, pass) { return config.authenticate(user, pass); @@ -100,7 +122,7 @@ module.exports = function(config_hash) { app.get('/:package/-/:filename', can('access'), function(req, res, next) { var stream = storage.get_tarball(req.params.package, req.params.filename); stream.on('error', function(err) { - return next(err); + return res.report_error(err); }); res.header('content-type', 'application/octet-stream'); stream.pipe(res); @@ -223,7 +245,7 @@ module.exports = function(config_hash) { }); stream.on('error', function(err) { - return next(err); + return res.report_error(err); }); stream.on('success', function() { res.status(201); @@ -250,15 +272,7 @@ module.exports = function(config_hash) { app.use(app.router); app.use(function(err, req, res, next) { - if (err.status && err.status >= 400 && err.status < 600) { - res.status(err.status); - res.send({error: err.msg || err.message || 'unknown error'}); - } else { - console.log(err); - console.log(err.stack); - res.status(500); - res.send({error: 'internal server error'}); - } + res.report_error(err); }); return app;