2017-10-20 35 views
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' }); 

我的问题是:

  1. 是我处理的自定义验证错误(如测试,如果电子邮件或密码字段为空),正确的方法,或者有更好的方式,因为我没有通过这些通过错误中间件?
  2. 如何处理承诺中的错误?

回答

1

可以测试新的承诺中的用户名和密码:

Promise.resolve().then(()=> { 
    if (!email || !password) { 
    throw new Error('You must provide email and password'); 
    } 
    return User.findOne({ email: email }) 
}) 

投掷内then功能的错误将停止执行,并调用连接到承诺第一catch。在你的情况下,用第一个参数next回调trowed错误。 Imo,你做得很好,它正确地在正确的中间件中表达应用程序发送客户端错误。

+0

为了澄清第二个问题,我需要验证“if(existingUser)”部分。 –

+0

我已经更新了我的回复,我希望那回答您的问题;) – jsan