const { PassThrough } = require('stream'); // This creates a read/write stream and returns it to the user. // If an error is thrown, the error should be emitted to the output stream. function getStream() { const outputStream = new PassThrough(); try { doSomething(); } catch (error) { outputStream.emit('error', error); // This line seems to throw another error, instead of just sending it to the output stream to be handled. } return outputStream; } // A function that throws an error function doSomething() { throw new Error('Some error is thrown'); } /** * User code */ const stream = getStream(); // This doesn't run because the `outputStream.emit()` call seems to throw another error inside the `catch` block. stream.on('error', (err) => { console.error('========================='); console.error(err); console.error('========================='); });