javascript - 如何防止 Firebase Cloud Function 崩溃以及如何发送错误消息作为响应?
问题描述
我创建了一个createUser
在调用时执行的简单函数。我有一个问题。当用户尝试使用已经存在的电子邮件注册时,该功能会崩溃。我的意思是,没关系,因为没有人希望有 2 个用户使用相同的电子邮件地址,但我想防止粉碎功能,相反,我想发送一条错误消息作为响应。
export const createUserTest = functions.https.onCall((data, context) => {
const {email, password} = data;
return new Promise((resolve, reject)=>{
try{
admin
.auth()
.createUser({
email: email,
emailVerified: false,
password: password,
disabled: false,
})
.then((user) => {
resolve({
result: 'success',
user: user,
}) ;
})
.catch((error) => {
reject(error) ;
});
}catch(error) {
reject (error)
}
})
});
我试图将功能放入try/catch
阻止,但它没有帮助。你知道我怎样才能实现我的目标吗?
解决方案
正如 Callable Cloud Functions 的文档中所解释的那样,“为确保客户端获得有用的错误详细信息,请通过抛出(或返回被拒绝的 Promise)实例从可调用对象中返回错误functions.https.HttpsError
。”
该错误的code
属性可以是此处列出的值之一。在您的情况下,最合适的似乎是already-exists
.
另一方面,您会在此处找到Admin SDK 身份验证错误列表,并且您会看到如果提供的电子邮件已被现有用户使用,则错误代码为auth/email-already-exists
。
因此,您可以按如下方式调整您的代码:
export const createUserTest = functions.https.onCall((data, context) => {
const { email, password } = data;
return admin
.auth()
.createUser({
email: email,
emailVerified: false,
password: password,
disabled: false,
})
.then((user) => {
return {
result: 'success',
user: user,
}
})
.catch((error) => {
if (error.code === 'auth/email-already-exists') {
throw new functions.https.HttpsError('already-exists', 'The provided email is already in use by an existing user');
} else {
throw new functions.https.HttpsError('...other code....', '...');
// If an error other than HttpsError is thrown, your client instead receives an error with the message INTERNAL and the code internal.
}
});
});
请参阅文档中的此处,如何在客户端处理错误。如果error.code == 'already-exists'
您知道这是因为电子邮件已在使用中。
推荐阅读
- python-3.x - 如何检测图像中记录的边界?
- javascript - 你能在 JavaScript 变量是 let 或 var 之后将其设为 const 吗?
- javascript - Promise 在代码块执行之前返回,问题只发生在 firefox 和 safari
- azure - 列出软删除的 Azure 存储帐户
- python - 相机在Python应用程序中启动太晚:原因是什么?
- c# - ASP.NET Web API 如何在单个控制器方法中一个一个发送多个 POST 请求?
- c# - 使用 new(...) 时没有争议的场景是什么?
- velo - 如何在 WIX 中更改产品页面中附加信息部分的颜色超链接?
- c# - 如何实现隐藏的抽象方法?
- c# - 如何在另一个项目中调用一个项目的方法?