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

106 Views Asked by At

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

There are 1 best solutions below

0
Miro On

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";
   }
})