我正在尝试使用firebase云函数作为webapp应用程序的后端。我尝试创建一个函数来创建一个用户,如下所示:
exports.createUser = functions.https.onCall(async (data, context) => {
//validate email
if (!verifyEmail(data.email))
throw new functions.https.HttpsError("invalid-argument", `The email ${data.email} is not formatted correctly`)
if (data.password !== data.confirmPassword)
throw new functions.https.HttpsError("invalid-argument", `Passwords do not match`)
if (!data.username)
throw new functions.https.HttpsError("invalid-argument", `Username cannot be empty`)
admin.auth().createUser({
email: data.email,
password: data.password
}).then(user => {
admin.firestore().collection('users').doc(user.uid).set({
username: data.username
}).catch(error => {
throw new functions.https.HttpsError("internal", `An internal error occured creating the user`, error)
})
}).catch(error => {
throw new functions.https.HttpsError("internal", `An internal error occured creating the user`, error)
})
})当传入格式不正确的电子邮件时,会将错误传递给用户,但是,如果在创建用户时发生故障,则会在后端日志中打印出错误,而不会发送给用户。有没有办法解决这个问题?
发布于 2021-02-27 08:33:14
您将async/await与.then()混合在一起,通常不推荐这样做,因为它会导致这种混淆。尝试如下所示:
exports.createUser = functions.https.onCall(async (data, context) => {
//validate email
if (!verifyEmail(data.email))
throw new functions.https.HttpsError("invalid-argument", `The email ${data.email} is not formatted correctly`)
if (data.password !== data.confirmPassword)
throw new functions.https.HttpsError("invalid-argument", `Passwords do not match`)
if (!data.username)
throw new functions.https.HttpsError("invalid-argument", `Username cannot be empty`)
try {
const user = await admin.auth().createUser({
email: data.email,
password: data.password
});
await admin.firestore().collection('users').doc(user.uid).set({
username: data.username
});
} catch (err) {
functions.logger.error("Unexpected error creating user", err);
throw new functions.https.HttpsError("internal", `An internal error occured creating the user`);
}
})https://stackoverflow.com/questions/66393916
复制相似问题