如何使用Oak捕获“listen”方法的错误?

huangapple go评论63阅读模式
英文:

How do I catch an error from the "listen" method with Oak?

问题

我试图在 Oak 中捕获错误,以便进行日志记录。如何使用 "app.listen" 方法捕获错误?我尝试使用 try/catch,但似乎 Deno 在我之前捕获了错误。

try {
  app.listen({ port: 3000 });
  logger.info('Listening...');
} catch (e) {
  handleTheError(e);
}
英文:

I am trying to catch an error in Oak for the purpose of logging. How do I catch an error with the "app.listen" method? I attempted to use try/catch but it seems like Deno catches the error before I can.

try{
  app.listen({port: 
  3000});
  logger.info('Listening...');
 }catch(e){
   handleTheError(e);
 }

答案1

得分: 1

如果您在任何处理程序之前设置此中间件,可能可以记录错误。

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    // 您可以在此处记录错误 .. 然后处理响应
    if (isHttpError(err)) {
      context.response.status = err.status;
    } else {
      context.response.status = 500;
    }
    context.response.body = { error: err.message };
    context.response.type = "json";
  }
});
英文:

if you set this middleware before any handler you may can log errors.

app.use(async (ctx,next)=>{
   try{
     await next();
   }catch(err){
      // You can log error here .. Then handle response
      if (isHttpError(err)) {
        context.response.status = err.status;
      } else {
        context.response.status = 500;
      }
      context.response.body = { error: err.message };
      context.response.type = "json";
   }
})

huangapple
  • 本文由 发表于 2023年6月26日 02:18:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定