help icon indicating copy to clipboard operation
help copied to clipboard

Custom Event Emmiter error handling

Open CarlosVilasAlvarez opened this issue 2 years ago • 1 comments

Details

Hi, I have been creating some custom implementations of Node's EventEmitter class. Do I have to wrap all its methods inside a try catch to emit the errors or is there a better way to emit all of them?

Take this one as an example:

    class CustomEmitter extends EventEmitter {
        doSomething() {
            try {
                // Faulty logic / data
                throw new Error('Something happened');
            } catch(error) {
                this.emit('error', error);
            }
        }

        doSomethingElse() {
            try {
                // Faulty logic / data
                throw new Error('Something happened');
            } catch(error) {
                this.emit('error', error);
            }
        }
     }

As you can see I have to wrap every method inside a try catch otherwise my node process will crash with an unhandled error. Is this the best approach?

Node.js version

16.13.2

Example code

No response

Operating system

MacOS 12.5.1

Scope

EventEmitter

Module and version

Not applicable.

CarlosVilasAlvarez avatar Sep 20 '22 16:09 CarlosVilasAlvarez

The most common use case for extending EventEmitter is to avail the event creation and event handling mechanism; as opposed to consuming an EventEmitter object, where we focus on event handling only. For example:

class CustomEmitter extends EventEmitter {
        doSomething() {
                // Faulty logic / data detected
                this.emit('an_event_that_reflects_faulty_logic', a_data_around_the_faulty_logic);
            }
     }

so that a consumer of this class can easily do:

CustomEmitter foo = ...;
foo.on('an_event_that_reflects_faulty_logic', a_data_around_the_faulty_logic) {
  // introspect the data and do the needful;
}

Your logic looks like you are wanting to capture the fully unexpected things that can happen at runtime, which is different from the bad things that can happen at runtime which are foreseen (by the author of the class). If this is indeed what you mean, then your logic is good; otherwise the above logic would be ideal for you.

Hope this helps.

gireeshpunathil avatar Sep 26 '22 03:09 gireeshpunathil