Koa.js - 错误处理

错误处理在构建 Web 应用程序中起着重要作用。Koa 也为此目的使用中间件。

在 Koa 中,您可以添加一个执行 try {yield next } 的中间件作为第一个中间件之一。如果我们在下游遇到任何错误,我们将返回到关联的 catch 子句并在此处处理错误。例如 −

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

//错误处理中间件
app.use(function *(next) {
   try {
      yield next;
   } catch (err) {
      this.status = err.status || 500;
      this.body = err.message;
      this.app.emit('error', err, this);
   }
});

//在下一个中间件中创建错误
//设置错误消息和状态代码并使用上下文对象抛出它

app.use(function *(next) {
    //这将设置状态和消息
    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

现在发送到服务器的任何请求都将导致此错误。