如何从Cloud Functions返回错误到Vue客户端?



在我的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并输出错误消息?

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

throw new functions.https。HttpsError("未知",就一定会犯错误。消息,犯错);

当你抛出一个错误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)
}

最新更新