【问题标题】:how to Handle promise error in nodeJS / express如何处理nodeJS / express中的promise错误
【发布时间】:2021-02-19 20:34:20
【问题描述】:

我正在构建一个nodeJS身份验证API,我在GitHub上找到了很多资源,我对编写和处理promise错误感到困惑,我想了解它以更改克隆项目上的一些代码。

第一个函数是位于注册服务上的注册:

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 错误?

【问题讨论】:

  • 快速提问,您是否在 路由器 中使用控制器来处理登录逻辑?
  • 这是我关注的链接,jasonwatmore.com/post/2020/05/13/…,我想稍微更改一下代码,例如如果帐户已经存在则返回错误

标签: node.js api error-handling promise middleware


【解决方案1】:

您将两种在 Javascript 中处理 promise 的方式合二为一

.catch 用于处理来自 .then 块的承诺拒绝。

使用 async-await 语法,我们需要使用 try-catch 块来处理 Promise 拒绝。

在您的注册函数中,只需将所有等待部分包装在一个 try-catch 块中即可处理。

【讨论】:

  • 感谢@r7r 的评论,我想了解如何更改代码以在我的逻辑中返回 409 状态代码响应,当执行注册函数时请求包含电子邮件时已经存在,我跟着此链接用于构建 api:jasonwatmore.com/post/2020/05/13/…
【解决方案2】:

您可以使用 throwcatch 将“帐户存在”条件作为错误处理。

但是,我会让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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2016-09-10
    • 2014-12-15
    • 1970-01-01
    • 2017-07-26
    • 2022-06-20
    • 2014-03-15
    相关资源
    最近更新 更多