javascript - Error handling and status codes with knex in koa -
i'm experimenting koa , knex build restful web service, , while got basics working i'm stuck @ handling errors. i'm using koa-knex-middleware wraps knex in generator.
i have following code defines happens , post requests 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, can't manage change http status codes. example, want return 201 post requests added item 400 malformed requests don't fit db schema.
i tried using tap()
, catch()
knex, wasn't able modify status code.
this.body = yield this.knex('equipment').insert(this.request.body).tap(function(){this.response = 204}.bind(this))
just hangs forever. same if try use .catch
set 400.
reading on koa @ first thought understood how supposed work, i'm not sure anymore. interaction of koa generators , promises knex confusing me.
is general approach sound, or mixing knex , koa way bad idea? , how handle errors , status codes combination?
you should able use 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; } });
Comments
Post a Comment