NestJS-在异常过滤器中返回ACK

时间:2020-05-14 10:40:53

标签: node.js websocket nestjs

我有以下示例:

@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()

中所做的一样

1 个答案:

答案 0 :(得分:0)

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

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测试。