【发布时间】:2019-04-07 10:58:11
【问题描述】:
下面的代码按预期运行。如果调用charge函数,该函数会从firestore获取相关票证对象,然后返回给客户端。
如果票证不存在,该函数将抛出 HttpsError 并带有错误消息,将由客户端解析。
exports.charge = functions.https.onCall(data => {
return admin.firestore().collection('tickets').doc(data.ticketId.toString()).get()
.then((snapshot) => {
return { ticket: snapshot.data() }
})
.catch((err) => {
throw new functions.https.HttpsError(
'not-found', // code
'The ticket wasn\'t found in the database'
);
});
});
问题出现在这之后。我现在需要使用 Stripe 向用户收费,这是另一个异步进程,将返回 Promise。收费需要第一个异步方法获取的定价信息,所以需要在检索到snapshot后调用。
exports.charge = functions.https.onCall(data => {
return admin.firestore().collection('tickets').doc(data.ticketId.toString()).get()
.then((snapshot) => {
return stripe.charges.create(charge) // have removed this variable as irrelevant for question
.then(() => {
return { success: true };
})
.catch(() => {
throw new functions.https.HttpsError(
'aborted', // code
'The charge failed'
);
})
})
.catch(() => {
throw new functions.https.HttpsError(
'not-found', // code
'The ticket wasn\'t found in the database'
);
});
});
我的问题是在新的charge 请求中捕获错误。似乎如果收费失败,它会成功调用第一个'aborted'catch,但随后将其传递给父catch,错误被覆盖,应用程序看到'ticket not found'错误。
我怎样才能阻止这种情况发生?我需要分别捕获这两个错误并为每个错误抛出一个HttpsError。
【问题讨论】:
标签: javascript node.js firebase promise google-cloud-functions