我正在尝试重构基于 Express 的简单 API 代码以使用 promise 而不是回调。我唯一的挑战是处理 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);
注意,我把这段代码注释掉了,因为它会抛出“发送后无法设置 header ”的错误:
return res.status(422).send({ error: 'Email is in use' });
我的问题是:
- 我处理自定义验证错误的方式(例如测试电子邮件或密码字段是否为空)是否正确,或者有更好的方法,因为我没有通过错误中间件传递这些错误?
- 如何处理 promise 中的错误?
最佳答案
您可以在新的 promise 中测试用户名和密码:
Promise.resolve().then(()=> {
if (!email || !password) {
throw new Error('You must provide email and password');
}
return User.findOne({ email: email })
})
在 then
函数中抛出错误将停止执行并调用附加到 promise 的第一个 catch
。在您的情况下, next
回调将 trowed 错误作为第一个参数。 Imo,你做得很好,这取决于在正确的中间件中适本地表达应用程序发送客户端错误。
关于javascript - Mongoose 处理 promise 调用和 Express 中间件中的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46847751/