Error handling Koaj是否可以在(';error';)回调中呈现错误页面?

Error handling Koaj是否可以在(';error';)回调中呈现错误页面?,error-handling,koa,Error Handling,Koa,只是检查一下,但似乎不可能在错误回调中呈现错误页面 app.on('error', function(err) { this.body = "ERROR: " + err.message; // this does not do anything }); 看来唯一的办法就是在中间产品中使用try-catch app.use(function *(next) { // return this.throw('TESTING ERROR') try { yield next;

只是检查一下,但似乎不可能在错误回调中呈现错误页面

app.on('error', function(err) {
  this.body = "ERROR: " + err.message; // this does not do anything
});
看来唯一的办法就是在中间产品中使用try-catch

app.use(function *(next) {
  // return this.throw('TESTING ERROR')
  try {
    yield next;
  } catch (err) {
    err.status = err.status || 500;
    err.message = err.message || 'An error occured';

    this.body = err.message;
  }
});

app.use(function *(next) {
  yield next;

  if (this.status === 404) {
    this.body = err.message;
  }
});

应用程序错误事件对于集中式错误处理和日志记录非常有用。事件的上下文(
)与请求上下文不同。但是,如果不再能够响应请求,则可能会将请求上下文传递给错误事件:

如果在req/res循环中出现错误,并且无法响应客户端,则还将传递上下文实例:

当发生错误,并且仍然可以对客户端作出响应时,也没有任何数据写入套接字,膝关节炎将以500的“内部服务器错误”适当地响应。在这两种情况下,都会发出应用程序级别的“错误”,以用于日志记录

使用中间件是捕获和响应错误的推荐方法。据报道

app.on('error', function(err, ctx){  
  log.error('server error', err, ctx);  
});