简体   繁体   English

如果有条件,然后在Node.js中引发错误,是否是一种好习惯?

[英]Is it good practice to use if conditional and then throw error in nodejs?

I started with nodejs recently and every code I find uses different structure. 我最近开始使用nodejs,发现的每个代码都使用不同的结构。 I was wondering if there is any problem using try/catch with async/await and how error handling should be done. 我想知道将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
            });
        }
    }
}

In the example above, I am feeling myself abusing of this "save something into variable, check it and if not, throw and error". 在上面的示例中,我感觉自己在滥用“将某些内容保存到变量中,检查它是否存在,否则抛出并出错”。

This is actually is okay to do so, But if I were you I will separate these logic which you were written inside that catch block in to a controller function in a separate file. 这样做实际上是可以的,但是如果您是我,我会将这些您在catch块中编写的逻辑分离到单独文件中的控制器函数中。 Other than that this is okay. 除此之外,还可以。

is it good practice for using async/await. 使用async / await是一个好习惯吗? you did good job. 你干得不错 I think so savedUser varibale not needed. 我认为这样saveUser varibale不需要。 You can save directly if any error throw it will be manage. 如果可以管理任何错误,则可以直接保存。

const newUser = new User(req.body);
 await newUser.save();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM