我尝试以各种可能的方式发送错误,但我得到的只是客户端的“内部”,我如何才能看到错误代码,以便向用户显示错误消息。
完整代码:
exports.createUserAndSetClaims = onCall(async (request) => {
try {
const userRecord = await getAuth().createUser({
email: request.data.email,
emailVerified: false,
password: request.data.password,
displayName: request.data.displayName,
disabled: false,
});
await getAuth().setCustomUserClaims(userRecord.uid, {
admin: request.data.isAdmin,
});
return { success: true, user: userRecord };
} catch (error) {
console.error("Error in createUserAndSetClaims:", error);
throw new functions.https.HttpsError(
error.code,
error.message
);
}
});
这就是我目前正在做的事情
// rest of the code
catch (error) {
console.error("Error in createUserAndSetClaims:", error);
throw new functions.https.HttpsError(
error.code,
error.message
);
}
我也尝试过这样发送:
throw new functions.https.HttpsError(
"internal",
"An error occurred",
{ code: error.code, message: error.message }
);
我可以在云函数日志上清楚地看到错误代码,但我无法在客户端读取它。 如果这很重要的话,我正在使用 flutter。
我了解您希望在 Callable Cloud Function 中抛出错误时传递特定的错误代码。正如文档中所解释的:
为了确保客户端获得有用的错误详细信息,请从 可通过抛出调用(或 Node.js 返回 Promise 被拒绝 with)
的实例或functions.https.HttpsError
。https_fn.HttpsError
错误有一个代码属性,可以是以下之一 gRPC 状态代码中列出的值。错误也有一个字符串 消息,默认为空字符串。他们还可以有一个 具有任意值的可选详细信息字段。
如果出现以下错误 您的函数(而非您的客户端)抛出 HTTPS 错误 收到错误消息 INTERNAL 和内部代码。
因此,为了在前端获取具有除默认内部错误代码之外的其他错误代码的错误,您需要选择此处列出的可能代码:gRPC 状态代码。
例如(来自文档):
// Checking attribute.
if (!(typeof text === "string") || text.length === 0) {
// Throwing an HttpsError so that the client gets the error details.
throw new HttpsError("invalid-argument", "The function must be called " +
"with one arguments \"text\" containing the message text to add.");
}
// Checking that the user is authenticated.
if (!request.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new HttpsError("failed-precondition", "The function must be " +
"called while authenticated.");
}