Wednesday, 3 October 2018

EventEmitter: Error handling of events

In any case, if the event emitter emits an error, then node.js application exit by printing stack trace.

Let us see this behavior with an example.

For example
myClockEmitter.emit("error", new Error("Error occured while handling the request"));

Above statement emits an error.

HelloWorld.js
var EventEmitter = require('events').EventEmitter;

class ClockEmitter extends EventEmitter {};

var myClockEmitter = new ClockEmitter();

myClockEmitter.on("hoursChange", (hour, minutes, seconds) => {
    console.log(`Hour changed: ${hour}:${minutes}:${seconds}`);
});


myClockEmitter.emit("error", new Error("Error occured while handling the request"));
myClockEmitter.emit("hoursChange", 1, 51, 23);
myClockEmitter.emit("hoursChange", 2, 51, 23);


When you ran above application, you will end up in below error.
events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: Error occured while handling the request
    at Object.<anonymous> (C:\Users\Krishna\Documents\Study\nodejs\examples\HelloWorld.js:12:30)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
    at startup (internal/bootstrap/node.js:266:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:596:3)
Emitted 'error' event at:
    at Object.<anonymous> (C:\Users\Krishna\Documents\Study\nodejs\examples\HelloWorld.js:12:16)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    [... lines matching original stack trace ...]
    at bootstrapNodeJSCore (internal/bootstrap/node.js:596:3)

How to handle the errors?
Just handle the error event like below.

myClockEmitter.on('error', (err) => {
  console.error('whoops! there was an error');
});

Find the below working application.

HelloWorld.js
var EventEmitter = require('events').EventEmitter;

class ClockEmitter extends EventEmitter {};

var myClockEmitter = new ClockEmitter();

myClockEmitter.on("hoursChange", (hour, minutes, seconds) => {
    console.log(`Hour changed: ${hour}:${minutes}:${seconds}`);
});

myClockEmitter.on('error', (err) => {
  console.error('whoops! there was an error');
});

myClockEmitter.emit("error", new Error("Error occured while handling the request"));
myClockEmitter.emit("hoursChange", 1, 51, 23);
myClockEmitter.emit("hoursChange", 2, 51, 23);


Output
whoops! there was an error
Hour changed: 1:51:23
Hour changed: 2:51:23




Previous                                                 Next                                                 Home

No comments:

Post a Comment