【问题标题】:Javascript: using catch block but not to handle an errorJavascript:使用 catch 块但不处理错误
【发布时间】:2020-12-16 21:28:38
【问题描述】:

我的情况是,我必须使用 catch 块来执行一些代码,但我不想将其视为错误。 基本上,我想分别根据用户是否已经注册来更新/创建用户。 admin sdk 让我创建一个用户,如果用户已经存在,它会抛出一个错误。因此,如果我在 catch 块中,我知道用户已经存在并且我想更新它。

function addClient(client) {
    return new Promise((resolve, reject) => {
        admin.auth().createUser({
            uid: client.id,
            email: client.email,
            emailVerified: true,
            password: client.password,
        }).then(record => {
            resolve(record);
            return null;
        }).catch(
            // the user already exist, I update it
            admin.auth().updateUser(client.id, {
                email: client.email
            }).then(record => {
                resolve(record);
                return null;
            }).catch(
                err => {
                    reject(err);
                }
            )
        );
    });
}

问题是,当我使用现有用户调用该函数时,它会正确更新,但 HTTP 响应是内部服务器错误(我猜是因为它进入了 catch 块并将其视为错误)。如果我发送一个新用户也是如此:它已正确创建,但 HTTP 响应代码是 500。 有办法避免这种行为吗?

这是为每个收到的用户调用前一个的主要函数,它负责发送 HTTP 响应:

exports.addClients = functions.https.onRequest((req, res) => {
    // fetch recevied list from payload
    var receivedClients = req.body.clients;

    var promises = [];

    receivedClients.forEach(client => {
        promises.push(addClient(client));
    })

    Promise.all(promises)
        .then(() => {
            res.sendStatus(200);
            return null;
        })
        .catch(err => {
            res.status(500).send(err);
        });
});

我想我想要实现的是让所有的承诺都得到解决。

【问题讨论】:

  • 您收到的错误信息是什么?
  • @Bergi 如果我向新用户发送错误代码是“auth/user-not-found”。如果我发送一个已经存在的用户,这是一个通用的“错误:无法处理请求”
  • 第一个是有道理的——你的addClient函数总是调用updateUser,看我的回答。

标签: javascript node.js asynchronous promise firebase-authentication


【解决方案1】:

您需要将回调传递给.catch,而不是承诺。还要避免Promise constructor antipattern!

function addClient(client) {
    return admin.auth().createUser({
        uid: client.id,
        email: client.email,
        emailVerified: true,
        password: client.password,
    }).catch(err => {
//           ^^^^^^^^
        // if (err.code != "UserExists") throw err;

        return admin.auth().updateUser(client.id, {
            email: client.email
        })
    });
}

【讨论】:

  • 我注意到您没有包含 admin.auth().updateUser 的 catch 块。我应该处理它还是它是好的?
  • @Fabio 你会如何处理它?目前,承诺为returned,错误只是冒泡,将在addClients 中捕获并由res.status(500).send(err) 处理。
猜你喜欢
  • 2023-01-10
  • 2013-01-21
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多