javascript - 使用 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
});
}
}
}
在上面的示例中,我感觉自己在滥用这种“将某些内容保存到变量中,检查它,如果不是,则抛出并出错”。
解决方案
这样做实际上是可以的,但如果我是你,我会将你在 catch 块中编写的这些逻辑分离到单独文件中的控制器函数中。除此之外,这没关系。
推荐阅读
- javascript - 无法在 EmberJS Fastboot beforeModel 中访问 window.location.search
- mysql - 无法将值插入 Heroku 数据库
- prolog - 动态列表中不同元素的总和并制作降序列表
- visual-studio - 还有两个与 VS Build Tools 和 VS 代理相关的问题
- reactjs - 如何在 React 中重新分配 Ref 对象
- javascript - 如何从angularjs上的xml响应中获取元素值
- file - 将“带转义字符”标签添加到 .txt 文件
- filter - FILTER 中的子条件使用非相关表
- angular - Angular Material mat-select multiselect dropdown 仅获取选中或未选中的项目
- ruby - 这段代码是用什么语言编写的?我将如何在 Ruby 中编写代码?