处理来自云功能Firebase中某些后台功能的意外故障

时间:2020-05-12 04:31:03

标签: javascript firebase google-cloud-functions

我下面有一个可调用的initiatePayment函数,该函数处理用户从客户端付款时的付款。如果付款成功(addNewRecord),此操作会将一个新文档记录到我的firestore数据库中,然后最终从请求的响应中返回付款数据。

export const initiatePayment = functions.https.onCall(async (data, context) => {
  // destructure data argument
  const { userId } = data;

  try {
    // 1. Process payment via external API request
    const payment = await paymentExternalRequest();
    const { paymentData, status } = payment.response;

    // 2. If payment processing was a success, record new payment data
    if (status === "succeeded") {
      addNewRecord(userId, paymentData);
    }

    // 3. Return paymentData to client
    return paymentData;
  } catch (error) {
    throw new functions.https.HttpsError("cancelled", "Cancelled", error);
  }
});

addNewRecord功能:

const addNewRecord = async (userId, paymentData) => {
  const newRecordToAdd = { userId, paymentData };
  const docRef = admin
    .firestore()
    .collection("transactions")
    .doc(paymentData.id);

  try {
    const newRecord = await docRef.set({ userId, transaction: newRecordToAdd });
    return newRecord;
  } catch (error) {
    console.log(error);
  }
};

我的问题是,如果addNewRecord失败,该如何处理它的错误并再次重试该函数以确保其成功?

1 个答案:

答案 0 :(得分:1)

考虑到您的代码,addNewRecord失败应该不会有问题。由于只有在特定且受控制的情况下才会调用该函数,因此您将拥有正确调用该函数所需的参数,所以应该没事。

无论如何,很可能一次失败,它将再次失败,因此,您可以尝试使用队列系统,而不仅仅是尝试重复执行。这样,您可以将该数据保留在队列中,并在检查和处理错误后再次运行,以确保将添加记录。

我建议您阅读以下有关Java排队的文档,相信会对您有所帮助。

让我知道信息是否对您有帮助!