![](/img/trans.png)
[英]Firebase Firestore transactions on cloud functions ( getAll method on the callback function first param ) How to use it?
[英]How to handle errors in Firestore transactions inside https cloud function?
如果某些先決條件失敗(在事務的讀取部分),我想向客戶端拋出 https 錯誤。 另外,如果事務由於意外錯誤而失敗,我想拋出“不可用”錯誤。
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."
);
});
問題是,如果我在 then 中拋出 https 錯誤,catch 會得到它並拋出另一個 https 錯誤。
拋出“失敗的前提條件”錯誤時如何避免進入捕獲?
我已經用 Promise.reject() 解決了這個問題
我知道這不是最好的方法,但有效。 尋找更好的方法。
await firestore
.runTransaction(async (transaction) =>
transaction.get(userRef).then((doc) => {
const { totalPoints } = doc.data();
if (totalPoints > 1000) {
...
} else {
return Promise.reject({
type: "failed-precondition",
message: "You have less than 1000 points."
});
}
})
)
.catch((err) => {
if (err.type === "failed-precondition") {
throw new functions.https.HttpsError(err.type, err.message);
}
else {
throw new functions.https.HttpsError(
"unavailable",
"Please, try again later."
);
}
});
對於我所有的 Cloud Functions,我有一個頂級 try-catch 可以捕獲未知錯誤並讓 HttpsError 錯誤繼續沿鏈繼續下去。
if (e instanceof https.HttpsError) throw e;
console.error("Encountered with an undefined error. Error: ", e);
throw new https.HttpsError(
"unknown",
"There was an unknown error."
);
你可以做類似的事情(當然用 functions.https.HttpsError 替換 https.HttpsError )。
這使我可以按原樣傳遞我在代碼中預定義的錯誤,並在為 Cloud Logging 記錄錯誤時向我的用戶提供錯誤消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.