Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid promise rejection when firing 'error' event with EventEmitter in nodejs?

I have code that looks like

var EventEmitter = require('events');

class MyClass extends EventEmitter{
    doSomething(){
        this.emit('error', new Error('this is why') );
    }
}


function doSomethingAsync(){
    return new Promise( (resolve,reject) =>{
        new MyClass().doSomething();
        resolve();
    });

}


process.on('unhandledRejection', function(reason){
    console.error('unhandled rejection', reason, reason.stack);
});


setTimeout( doSomethingAsync,1);

If I don't assign an error event handler with myClass.on('error', ()=>{ ... }) the unhandledRejection handler is triggered when the error event is thrown and doSomething flow is interrupted (I don't see the after print) if I add a handler, everything works fine (I do see the after print).

How can I avoid this? Why should an 'error' event cause a promise rejection?

sometimes I don't care if an event emitter throws an error event. but I will always care if a promise failed. is this wrong? should I treat them the same?

using nodejs 4.2.1

Edit

Ok, so I learned that node treats unhandled 'error' in a special way, and if unhandled it will throw an exception.

https://strongloop.com/strongblog/robust-node-applications-error-handling/

is there a way around it? I don't see why this choice of implementation in nodejs is correct.

shouldn't there be a global handler like unhandledErrorEvent instead? like they added to unhandledRejection?

like image 795
guy mograbi Avatar asked Sep 26 '22 11:09

guy mograbi


1 Answers

I agree, that is very annoying and I am gonna investigate that further in Node core.

In the meanwhile you can check for listeners with emitter.listeners(name), which is actually nice enough.

if (this.listeners('error').length > 0) this.emit('error', err)

I find your question to be a very good catch.

like image 142
eljefedelrodeodeljefe Avatar answered Sep 28 '22 07:09

eljefedelrodeodeljefe