【问题标题】:Validation Error Crashes App验证错误使应用程序崩溃
【发布时间】:2016-02-29 09:25:05
【问题描述】:

我将 Koa 和 Mongoose 用于我的 REST API。我的目标是使用适当的状态代码和错误消息进行响应。但是,应用程序在 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;
      }
    })
  });

【问题讨论】:

    标签: node.js mongoose koa


    【解决方案1】:

    使用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;
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 2021-10-03
      • 1970-01-01
      相关资源
      最近更新 更多