如何捕获流转换错误?

问题描述

这是可读流的本机定义

// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side.  You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk.  If you pass
// an error,then that'll put the hurt on the whole operation.  If you
// never call cb(),then you'll never get another chunk.
Transform.prototype._transform = function (chunk,encoding,cb) {
  throw new Error('_transform() is not implemented');
};

因此在您自己的定义中,当您想传递错误时,请致电cb(new Error('...'))

但是当我这样做时,如果通过管道传输,如何捕获它们?

我的意思是不使用process.on('uncaughtException')事件就可以正常捕获它们

解决方法

应通过添加.on("error",cb)处理程序,针对每个可读/可写的流分别处理流中的错误。

但是,节点还提供了一个实用程序功能,可以保证流中的错误处理。如果抛出错误,效用函数也负责销毁流:

import util from "util";
import stream from "stream";

await util.promisify(stream.pipeline)(
   new stream.Readable(),// a source
   new stream.Transform({
     transform: (chunk,encoding,callback) => {}
   }),new stream.Writable() // a sink
);