首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将异步函数中的firebase云函数错误发送给用户

将异步函数中的firebase云函数错误发送给用户
EN

Stack Overflow用户
提问于 2021-02-27 07:12:38
回答 1查看 22关注 0票数 0

我正在尝试使用firebase云函数作为webapp应用程序的后端。我尝试创建一个函数来创建一个用户,如下所示:

代码语言:javascript
复制
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)
    })
})

当传入格式不正确的电子邮件时,会将错误传递给用户,但是,如果在创建用户时发生故障,则会在后端日志中打印出错误,而不会发送给用户。有没有办法解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-27 08:33:14

您将async/await.then()混合在一起,通常不推荐这样做,因为它会导致这种混淆。尝试如下所示:

代码语言:javascript
复制
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`);
    }
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66393916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档