你如何捕获流转换错误?
How do you catch stream transform errors?
这是可读流本机定义
// 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)
处理程序为每个 readable/writable 单独处理流中的错误处理。
但是,node 还提供了一个实用函数,可以在流中承诺错误处理。如果抛出错误,效用函数也负责销毁流:
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
);
这是可读流本机定义
// 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)
处理程序为每个 readable/writable 单独处理流中的错误处理。
但是,node 还提供了一个实用函数,可以在流中承诺错误处理。如果抛出错误,效用函数也负责销毁流:
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
);