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()
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With