[英]How to catch/handle emitted errors within a series of pipes in nodejs?
我需要从数据源执行一系列转换。 如果在通过管道发送数据时发出错误,我需要适当地处理错误。 相反,响应只是挂起。
我可以关闭挂起响应的唯一方法是调用outStream.close(<string message here>)
,但这并没有多大用处,因为我想实际捕获正在发出的错误。
const seriesOfPipes = async () => {
try {
const streams = [transformStream1, transformStream2, transformStream3];
const res = await fetch("foo");
let outStream = res.body;
for (const streamItem of streams) {
outStream.on('error', streamItem.destroy.bind(streamItem));
outStream = outStream.pipe(streamItem);
}
return outStream;
} catch (e) {
// the error doesn't appear
console.log("you caught the error ", e.message);
}
};
我的响应挂起,因为响应处理程序没有关闭,我应该从一开始就意识到这一点。 此外, bind
不是必需的。 所以实际上错误事件处理程序应该做的是
outStream.on('error', (err) => {
// sanitize error here
const displayErr = sanitizeError(err);
// pass displayErr to express response object
resObj.writeHead(statusCode).end(JSON.stringify(displayErr);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.