【问题标题】:How do you catch stream transform errors?你如何捕捉流转换错误?
【发布时间】:2020-08-31 19:20:48
【问题描述】:

这是可读流原生定义

// 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') 事件以正常方式捕获它们

【问题讨论】:

  • 你的意思是 try...catch ?
  • 无法尝试捕获,因为流异步

标签: javascript node.js error-handling node-streams nodejs-stream


【解决方案1】:

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

不过,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
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2014-06-22
    • 2010-12-06
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    相关资源
    最近更新 更多