1
我正试图重构基于Express的简单API代码,以使用promises而不是回调函数。我唯一的挑战就是处理Mongoose验证错误(例如,如果用户存在,则进行测试)并将此错误引入中间件。在承诺调用和Express中间件中的Mongoose句柄验证错误
我通过一个中间件上index.js处理错误:
// Error handling middleware
app.use(function(err, req, res, next){
res.status(422).send({error: err._message})
});
这是一段代码,成功地处理了所有的边缘情况除外existingUser部分错误所在扔进遗忘,是
router.post('/signup', function(req, res, next) {
const email = req.body.email;
const password = req.body.password;
// Custom error
if (!email || !password) {
return res.status(422).send({ error: 'You must provide email and password'});
}
User.findOne({ email: email })
.then(function(existingUser) {
// If a user with email does exist, return an error
if (existingUser) {
// return res.status(422).send({ error: 'Email is in use' });
throw new Error('User already exists!');
}
// If a user with email does NOT exist, create and save user record
const user = new User({
email: email,
password: password
});
// save to database
return user.save()
})
.then(function(user) {
// Respond to request indicating the user was created
res.json({ token: tokenForUser(user) });
})
.catch(next);
注意我注释掉这段代码,因为它会抛出一个错误“无法设置头后,他们被送到”:
在响应中不可见return res.status(422).send({ error: 'Email is in use' });
我的问题是:
- 是我处理的自定义验证错误(如测试,如果电子邮件或密码字段为空),正确的方法,或者有更好的方式,因为我没有通过这些通过错误中间件?
- 如何处理承诺中的错误?
为了澄清第二个问题,我需要验证“if(existingUser)”部分。 –
我已经更新了我的回复,我希望那回答您的问题;) – jsan