Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to Handle Exception Globally in Node.js with Express 4?

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.

like image 672
Ashish Kumar Avatar asked Feb 22 '16 10:02

Ashish Kumar


People also ask

How do you handle exceptions globally?

The Controller Advice class to handle the exception globally is given below. We can define any Exception Handler methods in this class file. The Product Service API controller file is given below to update the Product. If the Product is not found, then it throws the ProductNotFoundException class.

How can you deal with error handling in Express JS explain with an example?

For example: app. get('/', (req, res) => { throw new Error('BROKEN') // Express will catch this on its own. }) If getUserById throws an error or rejects, next will be called with either the thrown error or the rejected value.

What is the preferred method of resolving unhandled exceptions in node JS?

Approach 1: Using try-catch block: We know that Node. js is a platform built on JavaScript runtime for easily building fast and scalable network applications. Being part of JavaScript, we know that the most prominent way to handle the exception is we can have try and catch block.


2 Answers

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)

like image 140
Yonatan Avatar answered Oct 26 '22 06:10

Yonatan


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.

like image 21
Swaraj Giri Avatar answered Oct 26 '22 06:10

Swaraj Giri