【问题标题】:NestJS - Return ACK in exception filterNestJS - 在异常过滤器中返回 ACK
【发布时间】:2020-08-30 20:47:13
【问题描述】:

我有以下例子:

@SubscribeMessage('v1-test')
@UsePipes(ValidationPipe)
@UseFilters(ValidationOnSocketExceptionFilter)
async test(
  @MessageBody() payload: payloadDTO,
  @ConnectedSocket() client: Socket,
){
   .....do stuff......
   return true;
}

这里是 ValidationOnSocketExceptionFilter:

 @Catch(BadRequestException)
export class ValidationOnSocketExceptionFilter
  implements ExceptionFilter<BadRequestException> {
  private readonly logger = new Logger(ValidationOnSocketExceptionFilter.name);

  constructor(private readonly customResponseService: CustomResponseService) {}

  catch(exception: BadRequestException, host: ArgumentsHost) {
    console.log('Validation err on socket');

    const client = host.switchToWs().getClient();

    // * get the msg from all validation erros
    let constraints: string[] | string;

    if (typeof exception.getResponse() === 'object') {
      let err: any = exception.getResponse();
      if (err.message && Array.isArray(err.message)) constraints = err.message;
    } else {
      constraints = exception.getResponse() as string;
    }

    const err: CustomResponse = this.customResponseService.buildErrorResponse(
      ErrCodes.BAD_PARAMETERS,
      constraints,
    );

    console.log(client);
    client.emit(SocketMessages.CustomError, err);
  }
}

我想要做的不是使用 client.emit(SocketMessages.CustomError, err); 创建和发送新事件,而是简单地使用 return err ,这意味着我想使用确认函数返回错误,就像我在函数 test()

中所做的一样

【问题讨论】:

    标签: node.js websocket nestjs


    【解决方案1】:

    您可以通过ArgumentsHost中的第三个参数获取回调函数。

    catch(exception: BadRequestException, host: ArgumentsHost) {
      // ...
    
      const err: CustomResponse = this.customResponseService.buildErrorResponse(
        ErrCodes.BAD_PARAMETERS,
        constraints,
      );
    
      const callback = host.getArgByIndex(2);
      if (callback && typeof callback === 'function') {
        callback(err);
      }
    }
    

    仅使用 @nestjs/platform-socket.io 测试。

    【讨论】:

    • 这对我有用。当我在我的守卫中抛出 WsException 时,它会作为单独的消息发送,称为“异常”。但是,当我按照此答案中的建议调用回调时,它会作为 ACK 发送。我本来希望异常在 socket.io 的上下文中作为 ACK 发送。这可能吗?
    • 刚刚看到这里的实现:github.com/nestjs/nest/blob/master/packages/websockets/… - 它正在调用发射。因此,为了获得 WsException 的 ACK,我刚刚创建了 SioException extends WsException,然后为 SioException 创建了一个 ExceptionFilter,它使用第三个参数回调而不是发出来响应。
    猜你喜欢
    • 2020-08-23
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2021-09-09
    • 2021-10-27
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多