I need to throw an error in a Transform stream.
Normally, I'd do this with the callback function on _transform()
. I can't in my situation because I need to throw the error even if no data is currently flowing through my stream. That is, if no data is flowing, _transform()
isn't getting called, and there's no callback I can call.
Currently, I'm emitting an error. Something like this:
import { Transform } from 'stream';
export default class MyTransformStream extends Transform {
constructor(opts) {
super(opts);
setTimeout(() => {
this.emit('error', new Error('Some error!'));
}, 10_000);
}
_transform(chunk, encoding, callback) {
this.push(chunk);
callback();
}
}
This seems to work fine. However, the documentation has a nice warning about it:
Avoid overriding public methods such as write(), end(), cork(), uncork(), read() and destroy(), or emitting internal events such as 'error', 'data', 'end', 'finish' and 'close' through .emit(). Doing so can break current and future stream invariants leading to behavior and/or compatibility issues with other streams, stream utilities, and user expectations.
Unfortunately, the documentation doesn't seem to suggest what to do instead.
What's the right way to throw this error outside of a _transform()
call?