Best way to Handle Exception Globally in Node.js with Express 4?
Solution 1
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)
Solution 2
In express, it's standard practice to have a catch all error handler attached. A barebones error handler would look like
// Handle errors
app.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.
Ashish Kumar
Updated on July 09, 2022Comments
-
Ashish Kumar almost 2 years
AS We have Exception filter in asp.net MVC, do we have similar kind of functionality in node.js with express 4 also?
I have tried following articles but didn't find the desired solution.
http://www.nodewiz.biz/nodejs-error-handling-pattern/
I have also tried below on app.js
process.on('uncaughtException', function (err) { console.log(err); })
ref article: http://shapeshed.com/uncaught-exceptions-in-node/
Any help would be appreciable.