I am pretty new to firebase cloud functions and javascript as a whole and i'm trying to get the hang of error handling within cloud functions. I wrote a function that simply takes data from a firestore document and updates another one. However when I test error scenarios the rejection isn't properly handled. The code below shows the function. Please what am i doing wrong??
exports.testFunction = functions.firestore.document('test/{docID}').onCreate(async(snap, context)=>{
const data = snap.data();
const name = data.name;
const age = data. age;
const id = context.params.docID;
return new Promise(async(res, rej)=>{
try{
await firestore.collection('testResults').add({
'name': name,
'age': age
});
await firestore.collection('test').doc(id).delete();
res();
}catch(e){
console.log(e);
rej();
}
});
});
CodePudding user response:
Firstly, there is rarely a reason to use new Promise
in JavaScript when you have async/await available with functions that already return promises. You should just let the existing promises returned by Firestore reject normally - there is no need to capture their errors if all you intend to do is log them. Cloud Functions will log the rejected promises.
All you really need to do is this:
const data = snap.data();
const name = data.name;
const age = data. age;
const id = context.params.docID;
await firestore.collection('testResults').add({
'name': name,
'age': age
});
await firestore.collection('test').doc(id).delete();
If you do need to capture the rejected promises from Firestore for whatever reason, you can use try/catch and just return a new rejection to fail the function correctly:
try {
await firestore.collection('testResults').add({
'name': name,
'age': age
});
await firestore.collection('test').doc(id).delete();
}
catch (e) {
return Promise.reject(e);
}