在可调用的 Firebase Cloud Function 中,我如何辨别抛出错误时要使用的代码?
In a callable Firebase Cloud Function, how do i discern which code to use when i throw an error?
当在 Firebase Cloud Function 中捕获错误时,Firebase documentation for handling errors 没有明确说明为失败 reads/writes 设置哪个错误代码是合适的Firestore.
给定以下函数:
exports.myCustomFunction = functions.https.onCall( async (data, context) => {
if (!context.auth) {
// Throwing this error is self explanatory and works as expected.
throw new functions.https.HttpsError("unauthenticated", "User must be authenticated.");
}
const uid = context.auth.uid;
const userQuery = admin.firestore().collection("users").where("userId", "==", uid);
try {
const user = await userQuery.limit(1).get();
// do stuff...
} catch (error) {
// ******* THIS IS THE ERROR I NEED HELP WITH *******
throw new functions.https.HttpsError("aborted", "user_query", {error: error});
}
});
如果我在上述函数中设置的 Firestore 查询失败,或者就此而言,如果 any Firestore read/write,或 Firestore 批处理集, 由于任何原因而失败,要设置的适当错误代码是什么?
选择似乎有限。应该是 aborted
还是 unknown
?
您可以传递给 HttpsError constructor are listed in the API documentation 的错误代码。如果您遇到您的代码现在或在可预见的将来无法解决的错误,通常您会使用“内部”,它转换为通常的 500 HTTP 状态代码。这让客户端知道出现了错误,这是后端的错误,不一定通过简单的重试就能解决。
当在 Firebase Cloud Function 中捕获错误时,Firebase documentation for handling errors 没有明确说明为失败 reads/writes 设置哪个错误代码是合适的Firestore.
给定以下函数:
exports.myCustomFunction = functions.https.onCall( async (data, context) => {
if (!context.auth) {
// Throwing this error is self explanatory and works as expected.
throw new functions.https.HttpsError("unauthenticated", "User must be authenticated.");
}
const uid = context.auth.uid;
const userQuery = admin.firestore().collection("users").where("userId", "==", uid);
try {
const user = await userQuery.limit(1).get();
// do stuff...
} catch (error) {
// ******* THIS IS THE ERROR I NEED HELP WITH *******
throw new functions.https.HttpsError("aborted", "user_query", {error: error});
}
});
如果我在上述函数中设置的 Firestore 查询失败,或者就此而言,如果 any Firestore read/write,或 Firestore 批处理集, 由于任何原因而失败,要设置的适当错误代码是什么?
选择似乎有限。应该是 aborted
还是 unknown
?
您可以传递给 HttpsError constructor are listed in the API documentation 的错误代码。如果您遇到您的代码现在或在可预见的将来无法解决的错误,通常您会使用“内部”,它转换为通常的 500 HTTP 状态代码。这让客户端知道出现了错误,这是后端的错误,不一定通过简单的重试就能解决。