Best way to Handle Exception Globally in Node.js with Express 4?
Errors might came from and caught in various locations thus it's recommended to handle errors in a centralized object that handles all types of errors. For example, error might occurs in the following places:
1.Express middleware in case of SYNC error in a web request
app.use(function (err, req, res, next) {//call handler here});
2.CRON jobs (scheduled tasks)
3.Your initialization script
4.Testing code
5.Uncaught error from somewhere
process.on('uncaughtException', function(error) { errorManagement.handler.handleError(error); if(!errorManagement.handler.isTrustedError(error)) process.exit(1)});
6.Unhandled promise rejection
process.on('unhandledRejection', function(reason, p){ //call handler here});
Then when you catch errors, pass them to a centralized error handler:
module.exports.handler = new errorHandler();function errorHandler(){ this.handleError = function (error) { return logger.logError(err).then(sendMailToAdminIfCritical).then(saveInOpsQueueIfCritical).then(determineIfOperationalError); }
For more information read bullet 4' here (+ other best practices and more than 35 quotes and code examples)
In express, it's standard practice to have a catch all error handler attached.A barebones error handler would look like
// Handle errorsapp.use((err, req, res, next) => { if (! err) { return next(); } res.status(500); res.send('500: Internal server error');});
Along with this, you will need to catch errors anywhere they can happen and pass them as a param in next()
. This will make sure that the catch all handler catches the errors.
To add global exceptions handlers in node are events on process. Use process.on
to catch them.
process.on('uncaughtException', (err) => { console.log('whoops! there was an error');});