ambelovsky / koa-socket-2

Socket.IO for Koa
https://www.npmjs.com/package/koa-socket-2
98 stars 14 forks source link

Bug: don't catch async error in middleware #11

Closed UchihaVeha closed 5 years ago

UchihaVeha commented 6 years ago
const middleware = (ctx, next) => {
  const { accessToken } = ctx.socket.socket.handshake.query;
  try {
    const { id } = jwt.verify(
      accessToken,
      config.auth.jwt.accessTokenSecretKey
    );
    ctx.userId = id;
    await next();
  } catch (err) {
    let error = 'internal error';
    if (err instanceof jwt.JsonWebTokenError) {
      error = 'authentication error';
    }
    if (ctx.acknowledge) {
      ctx.acknowledge({ success: false, error });
    } 
  }
}

chat.on(MESSAGES_FETCH_REQUEST, async ctx => {
  const payload = await Messages.findAll(ctx.data);
  ctx.acknowledge({ success: true, payload });
});

If some error happen in Messages.findAll(ctx.data), it doesn't appear in catch block of middleware because this in Socket:

 this.middleware( packet, () => { 
        handler( packet, data );
      });

if i replace on that, all work fine:

this.middleware( packet,  () =>  handler( packet, data ));

I just think you forgot to returning data from event handler?