diff --git a/lib/index.js b/lib/index.js index 4040cc929..891916800 100644 --- a/lib/index.js +++ b/lib/index.js @@ -38,9 +38,9 @@ module.exports = function(config_hash) { var app = express() - app.use(function(req, res, next) { + function error_reporting_middleware(req, res, next) { var calls = 0 - res.report_error = function(err) { + res.report_error = res.report_error || function(err) { calls++ if (err.status && err.status >= 400 && err.status < 600) { if (calls == 1) { @@ -56,8 +56,9 @@ module.exports = function(config_hash) { } } next() - }) + } + app.use(error_reporting_middleware) app.use(Middleware.log_and_etagify) app.use(function(req, res, next) { res.setHeader('X-Powered-By', 'Sinopia') @@ -285,6 +286,11 @@ module.exports = function(config_hash) { app.use(app.router) app.use(function(err, req, res, next) { + if (typeof(res.report_error) !== 'function') { + // in case of very early error this middleware may not be loaded before error is generated + // fixing that + error_reporting_middleware(req, res, function(){}) + } res.report_error(err) })