简体   繁体   中英

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. I was wondering if there is any problem using try/catch with async/await and how error handling should be done.

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. Other than that this is okay.

is it good practice for using async/await. you did good job. I think so savedUser varibale not needed. You can save directly if any error throw it will be manage.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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