【发布时间】:2018-02-19 11:00:01
【问题描述】:
我有一个功能来登录一个应该返回 JSON 的用户。
const username = req.body.username;
const password = req.body.password;
if (!username) {
throw new Error('Missing username');
}
if (!password) {
throw new Error('Missing password');
}
User.findOne({ username, password }).then(user => {
res.json({ user });
}).catch(err => {
res.json({ err });
});
但是在 JSON 中不返回缺少用户名或缺少密码的错误。
我可以改成
const username = req.body.username;
const password = req.body.password;
if (!username) {
res.json({ err: 'Missing username' });
}
if (!password) {
res.json({ err: 'Missing password' });
}
User.findOne({ username, password }).then(user => {
res.json({ user });
}).catch(err => {
res.json({ err });
});
不过好像有点多余。
将其封装在 Promise 中的正确方法是什么?
【问题讨论】:
标签: javascript json node.js error-handling promise