Koajs-error-handling

提供:Dev Guides
移動先:案内検索

Koa.js-エラー処理

エラー処理は、Webアプリケーションの構築において重要な役割を果たします。 Koaはこの目的にもミドルウェアを使用します。

Koaでは、最初のミドルウェアの1つとして\ try yield next **を行うミドルウェアを追加します。 ダウンストリームでエラーが発生した場合は、関連するcatch句に戻り、ここでエラーを処理します。 たとえば-

var koa = require('koa');
var app = koa();

//Error handling middleware
app.use(function *(next) {
   try {
      yield next;
   } catch (err) {
      this.status = err.status || 500;
      this.body = err.message;
      this.app.emit('error', err, this);
   }
});

//Create an error in the next middleware
//Set the error message and status code and throw it using context object

app.use(function *(next) {
  //This will set status and message
   this.throw('Error Message', 500);
});

app.listen(3000);

上記のコードで意図的にエラーを作成し、最初のミドルウェアのcatchブロックでエラーを処理しています。 これは、コンソールに送信されるとともに、クライアントへの応答として送信されます。 以下は、このエラーをトリガーしたときに表示されるエラーメッセージです。

InternalServerError: Error Message
   at Object.module.exports.throw
      (/home/ayushgp/learning/koa.js/node_modules/koa/lib/context.js:91:23)
   at Object.<anonymous> (/home/ayushgp/learning/koa.js/error.js:18:13)
   at next (native)
   at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:65:19)
   at/home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5
   at Object.co (/home/ayushgp/learning/koa.js/node_modules/co/index.js:50:10)
   at Object.toPromise (/home/ayushgp/learning/koa.js/node_modules/co/index.js:118:63)
   at next (/home/ayushgp/learning/koa.js/node_modules/co/index.js:99:29)
   at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:69:7)
   at/home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5

現在、サーバーに送信されたリクエストはすべてこのエラーになります。