写入时的异常处理


writable._write()writable._writev() 在执行期间发生的错误时,建议调用回调函数并传入错误对象作为第一个参数。 这样 Writable 就会触发 'error' 事件。 从 writable._write() 中抛出错误可能会导致无法预期的结果。 使用回调可以确保对错误进行一致且可预测的处理。

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

const myWritable = new Writable({
  write(chunk, encoding, callback) {
    if (chunk.toString().indexOf('a') >= 0) {
      callback(new Error('无效的数据块'));
    } else {
      callback();
    }
  }
});

It is recommended that errors occurring during the processing of the writable._write() and writable._writev() methods are reported by invoking the callback and passing the error as the first argument. This will cause an 'error' event to be emitted by the Writable. Throwing an Error from within writable._write() can result in unexpected and inconsistent behavior depending on how the stream is being used. Using the callback ensures consistent and predictable handling of errors.

If a Readable stream pipes into a Writable stream when Writable emits an error, the Readable stream will be unpiped.

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

const myWritable = new Writable({
  write(chunk, encoding, callback) {
    if (chunk.toString().indexOf('a') >= 0) {
      callback(new Error('chunk is invalid'));
    } else {
      callback();
    }
  }
});