简体   繁体   中英

Error handling and status codes with knex in koa

I'm experimenting with koa and knex to build a RESTful web service, and while I got the basics working I'm stuck at handling errors. I'm also using koa-knex-middleware that wraps knex in a generator.

I have the following code that defines what happens for GET and POST requests for a particular resource:

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);

This works in general, but what I can't manage to do is to change the HTTP status codes. For example, I want to return 201 for POST requests that added an item as well as 400 for malformed requests that don't fit to the DB schema.

I tried using tap() and catch() from knex, but I wasn't able to modify the status code.

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

just hangs forever. The same if I try to use .catch to set a 400.

Reading up on Koa at first I thought I understood roughly how it is supposed to work, but now I'm not so sure anymore. Especially the interaction of koa with generators and the promises from knex is seriously confusing me.

Is my general approach sound, or is mixing knex and koa this way a bad idea? And how exactly would I handle errors and status codes with this combination?

You should be able to use a standard try{}catch(err){} block.

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;
        }

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM