Koa.js - 錯誤處理



錯誤處理在構建 Web 應用程式中起著重要作用。Koa 還為此使用中介軟體。

在 Koa 中,將作為第一個中介軟體之一新增一個執行 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

現在,傳送到伺服器的任何請求都將導致此錯誤。

廣告