Node.js w / express callback error handling

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.

+4
source share
2 answers

See the connect-domain middleware. This will help you catch all the errors inside asynchronous callbacks, timeouts, etc. Only works with node> 0.8.0.

+1
source

Now I have finished creating the 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 demanding it in the modules he needs:

 var gh = require('../helpers/globalErrorHandler.js'); // Inside a callback if(err) { gh.globalErrorHandler(err, req, res); return; } 
+1
source

Source: https://habr.com/ru/post/1433322/


All Articles