How to handle errors in Firestore transactions inside https cloud function?

I want to throw an https error to the client if some pre-condition fails (in the read part of the transaction). Also, I want to throw an "unavailable" error if the transaction fails because of an unexpected error.

await firestore
  .runTransaction(async (transaction) =>
    transaction.get(userRef).then((doc) => {
        const { totalPoints } = doc.data();

        if (totalPoints > 1000) {
          ...
        } else {
          throw new functions.https.HttpsError(
            "failed-precondition",
            "You have less than 1000 points."
          );
        }
    })
  )
  .catch((err) => {
    throw new functions.https.HttpsError(
      "unavailable",
      "Please, try again later."
    );
  });

The problem is that, if I throw the https error inside the then, the catch will get it and throw an other https error.

How can I avoid entering the catch when throwing the "failed-precondition" error?

14 thoughts on “How to handle errors in Firestore transactions inside https cloud function?”

  1. 561487 545723Id require to verify with you here. Which is not 1 thing I typically do! I take pleasure in reading a submit that will make individuals think. Moreover, thanks for permitting me to remark! 310601

    Reply