title: Error handling and status codes with knex in koa
body: <p>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 <a href="https://github.com/tjwebb/koa-knex-middleware/blob/master/index.js" rel="nofollow">koa-knex-middleware</a> that wraps knex in a generator.</p>
  
  <p>I have the following code that defines what happens for GET and POST requests for a particular resource:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>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.</p>
  
  <p>I tried using <code>tap()</code> and <code>catch()</code> from knex, but I wasn't able to modify the status code.</p>
  
  <pre><code>    this.body = yield this.knex('equipment').insert(this.request.body).tap(function(){this.response = 204}.bind(this))
  </code></pre>
  
  <p>just hangs forever. The same if I try to use <code>.catch</code> to set a 400.</p>
  
  <p>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.</p>
  
  <p>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?</p>