2015-11-01 190 views
0

我正在試驗koa和knex來構建一個RESTful的Web服務,雖然我有基本的工作,我堅持在處理錯誤。我也使用koa-knex-middleware將knex包裝在一個生成器中。koa錯誤處理和狀態代碼與koa

我有下面的代碼,它定義了特定資源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,以便爲不符合數據庫模式的畸形請求添加項目以及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這種方式是一個壞主意?我該如何處理這種組合的錯誤和狀態碼?

回答

0

您應該可以使用標準的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; 
     } 

    });