首页 > 解决方案 > 使用 if 条件然后在 nodejs 中抛出错误是一种好习惯吗?

问题描述

我最近从 nodejs 开始,我发现的每个代码都使用不同的结构。我想知道将 try/catch 与 async/await 一起使用是否有任何问题,以及应该如何进行错误处理。

module.exports = {
    register: async function(req, res) {
        try {

            // Check if username already exists
            const usernameDB = await User.findOne({ username: req.body.username });
            if (usernameDB) throw new Error('Username already exists');

            // Check if email already exists
            const emailDB = await User.findOne({ email: req.body.email });
            if (emailDB) throw new Error('Email already exists');

            // Hash the password
            const salt = await bcrypt.genSalt(8);
            const hashPassword = await bcrypt.hash(req.body.password, salt);

            // Create a new User
            const newUser = new User({
                username: req.body.username,
                email: req.body.email,
                password: hashPassword
            });
            const savedUser = await newUser.save();
            if (!savedUser) throw new Error('Could not register you account, try again');

            res.status(201).send({
                success: true,
                message: 'Registered successfully'
            });

        }
        catch (err) {
            res.status(400).send({
                success: false,
                name: err.name,
                message: err.message
            });
        }
    }
}

在上面的示例中,我感觉自己在滥用这种“将某些内容保存到变量中,检查它,如果不是,则抛出并出错”。

标签: javascriptnode.jstry-catch

解决方案


这样做实际上是可以的,但如果我是你,我会将你在 catch 块中编写的这些逻辑分离到单独文件中的控制器函数中。除此之外,这没关系。


推荐阅读