Unhandled Rejection in Google Cloud Functions

北城余情 提交于 2021-01-27 13:47:29

问题


I got the following cloud function which works great. It's listening for an update in the real-time database and update Firestore accordingly.

Everything is fine, except when my user does not exist yet my Firestore database.

This where I need to deal with Unhandled rejection that I see in the Google Cloud Functions log.

So see below, in the shortened version of the function, for my db.collection("users").where("email", "==", email).get() how to stop the function to move forward and prevent the crash.

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

回答1:


You should use catch() on every promise that you return from your function that could be rejected. This tells Cloud Functions that you handled the error. The promise returned from catch() will be resolved.

Typically you log the error from catch() so you can see it in the console logs:

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


来源:https://stackoverflow.com/questions/48028366/unhandled-rejection-in-google-cloud-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!