bogushevich
bogushevich

Reputation: 23

Handle errors from EventEmitter

In class which inherits EventEmitter, we usually have two points to handle error.

someClass.on('error', function eventEmitterCallback(err){/* handle error*/});
//and
someClass.someAsyncAction(function asyncActionCallback(err){/* handle error*/})

We don't know, where error can appear, and what callback will execute. For example, tedious (module for MS SQL Server):

I want to create a simple function that will deligate all errors from module to first argument of callback.

function getSomeStuffFromDb(callback) { 
    var connection = new dbConnection(options);
    connection.on('error', callback);
    connection.connect(function(err) {
        if (err) return callback(err);
        /*exec SQL query*/
    }
}

Of course, if any error cause, I want to execute callback only once.How can I make this? How correctly union two points of error handling in one? Maybe if in my class I use class that inherits EventEmmiter, I need enherits my class from EventEmitter too.

Upvotes: 2

Views: 2650

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146064

Use the once event binding if you want to avoid running the same event handler over and over. Given your code sample, I don't believe once and on will behave any differently because the connection object is not long-lived, but it communicates the intention a touch more clearly. Then use a closure-scope flag to avoid both the event handler and callback responding to the same underlying error.

function getSomeStuffFromDb(callback) { 
    var handled = false;
    var connection = new dbConnection(options);
    connection.once('error', function (err) {
        if (err && !handled) {
            handled = true;
            return callback(err);
        }
    });
    connection.connect(function(err) {
        if (err) {
          if (handled) {
            return;
          } else {
            handled = true;
            return callback(err);
          }
        }
        /*exec SQL query*/
        callback();
    }
}

Upvotes: 1

Related Questions