簡體   English   中英

如何處理nodeJS/express中的promise錯誤

[英]how to Handle promise error in nodeJS / express

我正在構建一個 nodeJS 身份驗證 API,我在 GitHub 上找到了很多資源,我對編寫和 hundle promise 錯誤感到困惑,我想了解它以更改克隆項目上的一些代碼。

第一個函數是 register 位於 register service :

async function register(params, origin) {
    // validate
    if (await db.Account.findOne({ email: params.email })) {
        // send already registered error in email to prevent account enumeration
        return await sendAlreadyRegisteredEmail(params.email, origin);
    }

    // create account object
    const account = new db.Account(params);

    // first registered account is an admin
    const isFirstAccount = (await db.Account.countDocuments({})) === 0;
    account.role = isFirstAccount ? Role.Admin : Role.User;
    account.verificationToken = randomTokenString();

    // hash password
    account.passwordHash = hash(params.password);

    // save account
    await account.save();

    // send email
    await sendVerificationEmail(account, origin);
}

當帳戶已經注冊時,我想返回一個錯誤,不發送電子郵件(第 5 行)

帳戶控制器

這是我要處理從帳戶服務返回的承諾的控制器:

router.post('/register', registerSchema, register);
function register(req, res, next) {
    accountService.register(req.body, req.get('origin'))
        .then(() => res.json({ message: 'Registration successful, please check your email for verification instructions' }))
        .catch(next);
}

我認為 .catch 函數特征是一個被拒絕的承諾,不是嗎? .catch(next) 到底做了什么? 如果注冊時帳戶已經存在,如何返回帶有狀態代碼的 api 錯誤?

您將 Javascript 中處理 promise 的兩種方式合二為一

.catch 是處理來自 .then 塊的承諾拒絕。

使用 async-await 語法,我們需要使用 try-catch 塊處理承諾拒絕。

在您的 register 函數中,只需將所有 await 部分包裝在一個 try-catch 塊中,它將被處理。

您可以使用throw & catch將“帳戶存在”條件作為錯誤處理。

但是,我會讓register函數向調用者返回狀態消息或其他指示符,以便它可以以更靈活和可重用的方式使用。


async function register(params, origin) {
    // validate
    if (await db.Account.findOne({ email: params.email })) {
        // send already registered error in email to prevent account enumeration
        return {success: false, await sendAlreadyRegisteredEmail(params.email, origin)};
    }

    // create account object
    const account = new db.Account(params);

    // first registered account is an admin
    const isFirstAccount = (await db.Account.countDocuments({})) === 0;
    account.role = isFirstAccount ? Role.Admin : Role.User;
    account.verificationToken = randomTokenString();

    // hash password
    account.passwordHash = hash(params.password);

    // save account
    await account.save();

    // send email
    return {success: true, await sendVerificationEmail(account, origin)};
}

然后你可以在這里處理消息:

function register(req, res, next) {
    accountService.register(req.body, req.get('origin'))
        .then((results) => {
            if (results.success) {
                res.json({ message: 'Registration successful, please check your email for verification instructions' })
            } else {
               // send failure message
            }
        })
        .catch(next);
}

暫無
暫無

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

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