Google云端功能中的未处理拒绝

时间:2017-12-29 20:57:41

标签: firebase google-cloud-functions google-cloud-firestore

我有以下云功能,效果很好。 它正在侦听实时数据库中的更新并相应地更新Firestore。

一切都很好,除非我的用户还不存在我的Firestore数据库。

我需要处理我在Google云端功能日志中看到的Unhandled rejection

因此,请参阅下面的函数的缩短版本,我的db.collection("users").where("email", "==", email).get()如何停止函数前进并防止崩溃。

exports.updateActivities = functions.database.ref("delegates/{userId}/activities").onWrite((event) => {
    //Here I set all the needed variable   
    return rtdb.ref(`delegates/${userId}/email`).once("value", snapshot => {
            //Here I'm fine, email is always present.
        })
        .then(() => {
            db.collection("users").where("email", "==", email).get()

                //This is where I need to handle when there is not matching value, to stop moving forward.

                .then(querySnapshot => {
                    querySnapshot.forEach(val => {
                        console.log("Found match in FireStore " + val.id);
                        firestoreId = val.id;
                    })
                })
                .then(() => {
                    //Here I start my update on Firestore
                });
        })
});

2 个答案:

答案 0 :(得分:2)

您应该对从您的函数返回的可能被拒绝的每个承诺使用catch()。这告诉Cloud Functions您处理了错误。从catch()返回的承诺将得到解决。

通常,您从catch()记录错误,以便在控制台日志中看到它:

return somePromise
.then(() => { /* do your stuff */ }
.catch(error => { console.error(error) })

答案 1 :(得分:0)

我使用 bluebirdsuppressUnhandledRejections 来解决这个问题:

import Promise from 'bluebird';

function pool_push(pool, promise)
{
    // In Google Cloud there is a change to crash at `unhandledRejection`.
    // The following trick, basically, tells not to emit
    // `unhandledRejection` since `.catch` will be attached
    // a bit latter.
    const tmp = Promise.resolve(promise);
    tmp.suppressUnhandledRejections();
    pool.items.push(tmp);
}

export default pool_push;