I am new to node.js and expressing. In my app.js file, I have the following 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 a database server or otherwise cause an intermediate level error, but I'm not sure if it will also work when the callback receives an error message? I used something like this in my callbacks:
if(err) { console.log(err); res.send(500, {error: err}); }
but I would rather stick to the DRY principle and figure out a way to handle errors inside callbacks globally (via modules) instead of writing a bunch of the same code. If the catchall middleware doesn't work, do I stick with a global function for each module? Hope this makes sense.
Troy source share