Reputation: 1839
I'm new to node.js and express. I have the following in my app.js file as a last resort error handler:
app.use(function(err, req, res, next){
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
res.status(err.status || 500);
console.log(err);
var errMsg = "An internal error occurred. Please notify your system administrator.";
// respond with json
if (req.accepts('json')) {
res.send({error: errMsg});
return;
}
// respond with html page
if (req.accepts('html')) {
res.render('500', errMsg);
return;
}
res.type('txt').send(errMsg);
});
It works for me during testing when I kill the database server or otherwise induce a 'middleware' level error, but I'm not sure if it will also kick in when a callback receives an error? I've been using something like this inside my callbacks:
if(err) {
console.log(err);
res.send(500, {error: err});
}
but I'd like to better adhere to the DRY principle and figure out a way to handle errors inside callbacks globally (across modules) instead of writing a bunch of the same code. If the middleware 'catchall' won't work, am I stuck with a global function per module? Hope this make sense.
Upvotes: 4
Views: 1864
Reputation: 1839
For now I ended up just creating a global error handler module:
exports.globalErrorHandler = function(err, req, res) {
if(!err || !req || !res) return;
console.log(err);
var errMsg = "An internal error occurred. Please notify your system administrator.";
// respond with json
if (req.accepts('json')) {
res.send({error: errMsg});
return;
}
// respond with html page
if (req.accepts('html')) {
res.render('500', errMsg);
return;
}
res.type('txt').send(errMsg);
}
and requiring it in the modules that need it:
var gh = require('../helpers/globalErrorHandler.js');
// Inside a callback
if(err) {
gh.globalErrorHandler(err, req, res);
return;
}
Upvotes: 1
Reputation: 26179
Look at connect-domain middleware. It helps you to catch all errors inside of asynchronous callbacks, timeouts, etc. Works only with node > 0.8.0.
Upvotes: 1