读取时的异常处理


readable._read() 在执行期间发生的错误时,建议触发 'error' 事件而不是抛出错误。 从 readable._read() 中抛出错误可能会导致无法预期的结果。 使用'error' 事件可以确保对错误进行一致且可预测的处理。

const { Readable } = require('stream');

const myReadable = new Readable({
  read(size) {
    if (checkSomeErrorCondition()) {
      process.nextTick(() => this.emit('error', err));
      return;
    }
    // 各种处理。
  }
});

It is recommended that errors occurring during the processing of the readable._read() method are emitted using the 'error' event rather than being thrown. Throwing an Error from within readable._read() can result in unexpected and inconsistent behavior depending on whether the stream is operating in flowing or paused mode. Using the 'error' event ensures consistent and predictable handling of errors.

const { Readable } = require('stream');

const myReadable = new Readable({
  read(size) {
    if (checkSomeErrorCondition()) {
      process.nextTick(() => this.emit('error', err));
      return;
    }
    // do some work
  }
});