我有这个 TypeScript 代码(针对最相关的部分进行了编辑):
try {
await this.downloadSourcePicStreamToS3('url', 'filename');
} catch (e) {
console.log(e);
return;
}
而 downloadSourcePicStreamToS3 是这样的:
private downloadSourcePicStreamToS3(url: string, filename: string): Promise<void> {
const bytecount = () => {
let size = 0;
const passThrough = new stream.PassThrough();
passThrough.on('data', chunk => {
size += Buffer.byteLength(chunk);
if (size > 60_000_000) {
throw 'TOO_BIG';
}
});
return passThrough;
};
return new Promise((resolve, reject) => {
stream.pipeline(
got.stream(url, {...}),
bytecount(),
this.s3.uploadSourcePicStream(filename),
err => {
if (err) {
reject(err);
} else {
resolve();
}
}
);
});
}
基本上,它只是检查作为流下载的文件是否太大,如果是则抛出错误。
但不知何故,当我在一个太大的文件上运行它时,我得到 ERROR Uncaught Exception "TOO_BIG"
。
我尝试通过抛出一个正确的异常 (throw new Error('too big')
),同样的事情(显然是一个 Error 对象除外)。我也尝试过“承诺”管道(pipeline = util.promisify(stream.pipeline);
),同样如此。
我发现的唯一类似问题是 How come node.js doesn't catch my errors?,但它已经很老了,并没有真正解决。我不想使用 uncaughtException
事件,因为没有理由不首先捕获此异常...知道如何使其成功捕获吗?