[英]Is it good practice to use if conditional and then throw error in 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
});
}
}
}
在上面的示例中,我感覺自己在濫用“將某些內容保存到變量中,檢查它是否存在,否則拋出並出錯”。
這樣做實際上是可以的,但是如果您是我,我會將這些您在catch塊中編寫的邏輯分離到單獨文件中的控制器函數中。 除此之外,還可以。
使用async / await是一個好習慣嗎? 你干得不錯 我認為這樣saveUser varibale不需要。 如果可以管理任何錯誤,則可以直接保存。
const newUser = new User(req.body);
await newUser.save();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.