Reputation: 583
A common pattern in my Express app is to include the following in all my routes:
//...code which could result in an err
if (!err) return res.send(200);
console.log(err); // Would prefer to omit this line
res.send(500);
Right now, I need to write console.log(err)
in all my routes. I'd prefer to just automatically log the err
variable every time a 500 is sent. Is there any way to hook into Express and automatically log the call stack and/or err
for all 500 responses?
Upvotes: 4
Views: 3605
Reputation: 17680
From your explanation, you seem to be including error handling in all your routes. You probably should create a global interceptor error handler which can perform the logging for you and still be the base error handler if you have a 500 error type.
//if your express var is app
var errorHandler = function(err, req, res, next){
console.log(err.stack);
res.send(500);
// or you could call res.render('error'); if you have a view for that.
};
app.use(app.router); // this has to come before your interceptors
app.use(notFound); // your page not found interceptor
app.use(errorHandler);
Upvotes: 6