簡體   English   中英

Javascript:使用 catch 塊但不處理錯誤

[英]Javascript: using catch block but not to handle an error

我處於必須使用 catch 塊來執行某些代碼的情況,但我不想將其視為錯誤。 基本上,我想分別根據用戶是否已經注冊來更新/創建用戶。 管理員 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);
                }
            )
        );
    });
}

問題是,當我與現有用戶一起調用 function 時,它已正確更新,但 HTTP 響應是內部服務器錯誤(我猜是因為它進入了 catch 塊並將其視為錯誤)。 如果我發送一個新用戶也是如此:它已正確創建,但 HTTP 響應代碼為 500。有辦法避免這種行為嗎?

這是主要的 function 為收到的每個用戶調用前一個,它負責發送 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);
        });
});

我想我想要實現的是讓所有的承諾都得到解決。

您需要將回調傳遞給.catch ,而不是 promise。 還要避免Promise構造函數反模式

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
        })
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM