Skip to content

Latest commit

 

History

History
30 lines (23 loc) · 1.12 KB

File metadata and controls

30 lines (23 loc) · 1.12 KB

detect unhandled error events (detect-unhandled-error-events)

When using the EventEmitter, it cannot be denied that errors can occur anywhere in the chain.

Given this code below:

const EventEmitter = require('events')
const myEmitter = new EventEmitter()

myEmitter.emit('error', new Error('whoops!'))
// Throws and crashes Node.js

Since there is no error event listener called, the error will be thrown and will be treated as an uncaughtException. Once an error is emitted and unhandled, the Node.js application will crash.

There should always be listeners for events at the least. This of course does not count out error events.

const EventEmitter = require('events')
const myEmitter = new EventEmitter()
// MUST: include error listener
myEmitter.on('error', (err) => {
    console.error('An error occurred')
}) 
myEmitter.emit('error', new Error('whoops!'))
// Prints: An error occurred

link 1 link 2