英文:
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";
   }
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论