[英]How can I send a custom response from a firebase cloud function?
[英]How to prevent Firebase Cloud Function from crashing and how to send error message as response?
我创建了一个简单的createUser
function,它在调用时执行。 我有一个问题。 当用户尝试向已经存在的 email 注册时,function 崩溃。 我的意思是,没关系,因为没有人希望有 2 个用户具有相同的 email 地址,但我想防止破坏 function,相反,我想发送一条错误消息作为响应。
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)
}
})
});
我试图将 function 放入try/catch
块,但没有帮助。 你知道我怎样才能实现我的目标吗?
如可调用云函数的文档中所述,“为确保客户端获得有用的错误详细信息,请通过抛出(或返回被拒绝的 Promise 拒绝) functions.https.HttpsError
实例从可调用返回错误。https.HttpsError ”。
该错误的code
属性可以是此处列出的值之一。 在您的情况下,最合适的似乎是already-exists
。
另一方面,您会在此处找到管理员 SDK 身份验证错误列表,并且您会看到如果提供的 email 已被现有用户使用,则错误代码为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'
你知道这是因为 email 已经在使用中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.