如何捕获从stream引起的错误。
下面是代码片段,其中有一个包含 uuid 的巨大文件,我想逐行读取并对其进行处理。
try {
const downloadedFile = this._s3client.getObject(params)
const userStream: Readable = await downloadedFile.createReadStream()
for await (const userId of pipeline(userStream, split2(), piplineCallback)) {
console.log(userId)
}
} catch (error) {
console.log('Error should be caught here.')
throw error
}
const piplineCallback = (err) => {
if (err) {
logger.error({ exception: err }, 'Error occured in splitted userstream pipeline.')
throw new InternalServerError(err)
} else {
logger.debug('Userstream pipeline succeded.')
}
}
当管道 API 抛出错误时,它不会进入 catch 块,而是到达我的服务器 index.ts,并在“uncaughtException”事件中捕获。
我正在寻找一种方法来捕获类的 try catch 块中的所有流错误,因为我需要在那里进行一些特殊处理。
Below is the code snippet where a huge file with uuids I want to read line by line and do processing on it.
try {
const downloadedFile = this._s3client.getObject(params)
const userStream: Readable = await downloadedFile.createReadStream()
for await (const userId of pipeline(userStream, split2(), piplineCallback)) {
console.log(userId)
}
} catch (error) {
console.log('Error should be caught here.')
throw error
}
const piplineCallback = (err) => {
if (err) {
logger.error({ exception: err }, 'Error occured in splitted userstream pipeline.')
throw new InternalServerError(err)
} else {
logger.debug('Userstream pipeline succeded.')
}
}
When there is an error thrown from pipeline API it does not goes into catch block but rather reaches my server index.ts where it gets caught in 'uncaughtException' event.
I am looking for a way to be able to catch all the stream errors in my class's try catch block as I need to do some special handling there.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

通过承诺管道并等待流数据完全被消耗,可以在 try-catch 中捕获在
stream.pipeline()
中抛出的错误。请注意,
stream
和util
是内置的 Nodejs 库。Errors thrown in a
stream.pipeline()
may be captured in the try-catch by promisifying the pipeline and awaiting the streamed data to be consumed entirely.Note that
stream
andutil
are built-in Nodejs libraries.