首页 > 解决方案 > NestJS - 在异常过滤器中返回 ACK

问题描述

我有以下示例:

@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.jswebsocketnestjs

解决方案


您可以通过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.


推荐阅读