【问题标题】:How to return an error from Cloud Functions to Vue client?如何从 Cloud Functions 向 Vue 客户端返回错误?
【发布时间】:2021-05-09 10:35:31
【问题描述】:

在我的 Vue 应用程序中,用户输入他们的账单信息,然后我将其传递给 Google Cloud Function,它会更新 Stripe 中的客户对象。我的问题是,如果函数出现问题,我该如何返回错误,以便向用户显示错误消息?

这是实际的功能...

exports.updateStripeCustomer = functions.https.onCall(async (data, context) => {
  const { details, customerId } = data;
  const uid = context.auth.uid;

  try {
    const customer = await stripe.customers.update(customerId, {
      name: details.name,
      email: details.email,
      address: {
        line1: details.line1,
        line2: details.line2,
        city: details.city,
        state: details.state,
        postal_code: details.postCode,
        country: details.country
      }
    });

    return;
  } catch (err) {
    throw new functions.https.HttpsError('unknown', err.message, err);
    return err;
  }
});

然后,在客户端:

const updateCus = projectFunctions.httpsCallable('updateStripeCustomer');
const res = await updateCus({ 
  details: profile.value.details,
  customerId: profile.value.billing.customerId
});

console.log(res)

该功能正常工作,但如果在任何时候 Stripe 返回错误,我可以在客户端控制台上看到它,但 console.log(res) 甚至没有运行...

返回错误的正确方法是什么,以便我可以检查 res 并输出错误消息?

【问题讨论】:

    标签: javascript firebase vue.js async-await google-cloud-functions


    【解决方案1】:

    下面的行足以告诉客户错误;你应该删除return err;

    抛出新函数.https.HttpsError('unknown', err.message, err);

    每当您抛出错误functions.https.HttpsError 时,您也必须在客户端捕获它。当您使用 async/await 时,请将您的代码包装在 try/catch 块中。

    try {
        const res = await updateCus({ 
           details: profile.value.details,
           customerId: profile.value.billing.customerId
         });
    } catch (error) {
        console.log(error)
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 2022-01-08
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 2021-11-18
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多