【问题标题】:Error handling and status codes with knex in koakoa 中 knex 的错误处理和状态码
【发布时间】:2015-11-01 15:37:14
【问题描述】:

我正在尝试使用 koa 和 knex 来构建一个 RESTful Web 服务,虽然我已经掌握了基础知识,但我一直在处理错误。我还在使用 koa-knex-middleware 将 knex 包装在生成器中。

我有以下代码定义了对特定资源的 GET 和 POST 请求会发生什么:

var koa = require('koa');
var koaBody = require('koa-body')();
var router = require('koa-router')();
var app = koa();

var knex = require('./koa-knex');

app.use(knex({
    client: 'sqlite3',
    connection: {
        filename: "./src/server/devdb.sqlite"
    }
}));

router
    .get('/equipment', function *(next){
        this.body = yield this.knex('equipment');
    })
    .post('/equipment', koaBody, function *(next){
        this.body = yield this.knex('equipment').insert(this.request.body)
    });

app.use(router.routes()).use(router.allowedMethods());

app.listen(4000);

这通常有效,但我无法更改 HTTP 状态代码。例如,我想为添加项目的 POST 请求返回 201,为不适合 DB 架构的格式错误的请求返回 400。

我尝试使用 knex 的 tap()catch(),但无法修改状态码。

    this.body = yield this.knex('equipment').insert(this.request.body).tap(function(){this.response = 204}.bind(this))

只是永远挂起。如果我尝试使用 .catch 设置 400 也是一样。

起初阅读 Koa,我以为我大致了解它应该如何工作,但现在我不再那么确定了。尤其是 koa 与生成器的交互以及 knex 的承诺让我非常困惑。

我的一般方法是否合理,或者以这种方式混合 knex 和 koa 是个坏主意?以及我将如何使用这种组合来处理错误和状态代码?

【问题讨论】:

    标签: javascript koa knex.js


    【解决方案1】:

    您应该能够使用标准的try{}catch(err){} 块。

    https://github.com/tj/co#examples

    vrouter
        .get('/equipment', function *(next){
            this.body = yield this.knex('equipment');
        })
        .post('/equipment', koaBody, function *(next){
            try{
              this.body = yield this.knex('equipment').insert(this.request.body)
              this.status = 201;
            }
            catch(err){
              this.throw(400, 'malformed request...');
              // or
              // this.status = 400;
            }
    
        });
    

    【讨论】:

      猜你喜欢
      • 2018-08-20
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 2020-07-05
      • 1970-01-01
      相关资源
      最近更新 更多