Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS - Return ACK in exception filter

I have the following example:

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

And here is the 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);
  }
}

What I want to do is not create and send a new event using client.emit(SocketMessages.CustomError, err);, but rather to simple use return err, meaning that I want to return the error using the acknowledgement function, same I'm doing inside the function test()

like image 330
Georgian Stan Avatar asked Sep 01 '25 02:09

Georgian Stan


1 Answers

You can get callback function through 3rd argument in 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);
  }
}

Tested only with @nestjs/platform-socket.io.

like image 157
Alexey Kharin Avatar answered Sep 02 '25 17:09

Alexey Kharin