验证错误崩溃应用程序
问题描述:
我为我的REST API使用Koa和Mongoose。我的目标是用适当的状态码和错误信息进行回应。但是,应用程序在ValidationError上兑现,电子邮件是必填字段,但未在此请求中提供。如何与其他一个状态码500多家验证错误崩溃应用程序
router.post('/user/', function *() {
var user = new User(this.request.body);
yield user.save((error) => {
if (error) {
//Does not respond with a 404
this.status = 404;
} else {
this.status = 201;
this.response.body = user;
}
})
});
答
一个伟大的事情有关使用yield
是,你可以使用try {} catch() {}
就像你写的代码同步。
所以,你的代码就变成了:
router.post('/user/', function *() {
var user = new User(this.request.body);
try {
yield user.save();
}
catch (err) {
//Does not respond with a 404
this.status = 404;
}
this.status = 201;
this.response.body = user;
});