【发布时间】:2018-12-27 18:47:55
【问题描述】:
我知道有很多关于此错误的帖子,其中大多数都有相同的答案,但不知何故我仍然收到警告。
我读过类似In Node.js 7 what is the proper way to suppress UnhandledPromiseRejectionWarning? 的内容,但由于事件侦听器泄漏,我使用once 而不是on,但不知何故我有时仍会看到警告
我确实想摆脱警告或解决它,因为它的说法将来会被弃用,但不确定何时。
起初我第一次跑步时,我会先得到这个
You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection: myrejectionmessage
然后,我会得到这个错误
UnhandledPromiseRejectionWarning: myrejectionmessage
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 5)
这是我的原始代码,没有我尝试过的帖子,我试图在aws s3 bucket 中获取一些文件,但桶中的文件可能不存在
这个功能是比较是否有文件然后比较修改时间,如果文件不存在reject
exports.compareObjectMT = (s3, Key, getFileStat) => {
const s3GetParams = {
Bucket: process.env.S3_BUCKET,
Key,
};
return new Promise((res, rej) => {
s3.getObject(s3GetParams, (err, data) => {
if (err) rej('myrejecterror');
if (data) {
res(String(getFileStat.mtimeMs) === data.Metadata.mtimems);
}
res(false);
});
});
};
提前感谢您的任何建议
这就是我使用函数的方式
exports.s3Put = async (path) => {
try {
fs.readFile(path, async (err, fileBinary) => {
if (err) throw err;
// console.log(data, 'data');
const s3 = new AWS.S3();
const Key = path.replace(process.env.WATCH_PATH, '');
const getStat = await getFileStat(path);
console.log(getStat, 'getstateeeeeeeeeeeeeeee');
const compareObj = await compareObjectMT(s3, Key, getStat);
console.log(compareObj, 'compareObj');
});
} catch (e) {
console.log(e, 'errorrrrrrrrrrrrr');
}
};
【问题讨论】:
-
您需要
compareObjectMT的消费者来捕获错误。 -
@CertainPerformance 我确实尝试将函数的内部包裹在
const s3Get..... 直到函数结束时使用try catch though -
不是
try/catch,而是.catch,Promise方法
标签: javascript node.js error-handling es6-promise