unhandledRejection Node.js

时间:2018-12-27 07:43:57

标签: javascript node.js error-handling es6-promise

我知道有很多关于此错误的帖子,其中大多数都具有相同的答案,但不知何故我仍然收到警告。

我已经读过类似In Node.js 7 what is the proper way to suppress UnhandledPromiseRejectionWarning?的内容,但由于事件监听器泄漏,我使用on而不是once,但有时我还是会看到警告

我确实想获得警告或解决该警告,因为它的说法将来会被弃用,但不确定何时。

当我第一次跑步时,我会先获得这个

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');
    }
};

1 个答案:

答案 0 :(得分:1)

//calling compareObjectMT ,Your return value is a Promise Object either resolve/reject

//s3, Key, getFileStat aruments value you are passing

compareObjectMT(s3, Key, getFileStat).then((value)=>{do something}) 
                                     .catch((err)=>console.error(err))

您正在做的事情与此类似。.读取文件内的回调后,尝试catch ..它将不会捕获来自等待状态的拒绝错误

您可能会把所有等待放在单个try catch块中

exports.s3Put = async (path) => {
try {
    fs.readFile(path, async (err, fileBinary) => {
        if (err) throw err;
        // console.log(data, 'data');
         try {
        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');
}
    });
} catch (e) {
    console.log(e, 'errorrrrrrrrrrrrr');
}

};

enter image description here