I'm trying to add some validation to my WebSocketGateway in NestJS. Here's the code:
// MessageDTO
import { IsNotEmpty, MinLength } from 'class-validator';
export class MessageDTO {
@IsNotEmpty()
username: string;
@IsNotEmpty()
@MinLength(10)
text: string;
}
// Gateway
import { ValidationPipe, UsePipes } from '@nestjs/common';
import { MessageBody, SubscribeMessage, WebSocketGateway, WsResponse } from '@nestjs/websockets';
import { MessageService } from './message/message.service';
import { MessageDTO } from './message/message.dto';
import { Message } from './message/message.entity';
@WebSocketGateway()
export class AppGateway {
constructor(private readonly messageService: MessageService) {}
@UsePipes(new ValidationPipe())
@SubscribeMessage('message')
async handleMessage(@MessageBody() dto: MessageDTO): Promise<WsResponse<Message>> {
const message = await this.messageService.saveMessage(dto);
return { event: 'message', data: message };
}
}
Now, when I try to send a message that doesn't meet validation rules, it errors out, but the client always receives { status: 'error', message: 'Internal server error'}. Also, Nest logs the error to the console (which I belive should not happen...?):
thing_api | Error: Bad Request Exception
thing_api | at ValidationPipe.exceptionFactory (/usr/src/app/node_modules/@nestjs/common/pipes/validation.pipe.js:78:20)
thing_api | at ValidationPipe.transform (/usr/src/app/node_modules/@nestjs/common/pipes/validation.pipe.js:50:24)
thing_api | at processTicksAndRejections (internal/process/task_queues.js:89:5)
thing_api | at async resolveParamValue (/usr/src/app/node_modules/@nestjs/websockets/context/ws-context-creator.js:104:31)
thing_api | at async Promise.all (index 0)
thing_api | at async pipesFn (/usr/src/app/node_modules/@nestjs/websockets/context/ws-context-creator.js:106:13)
thing_api | at async /usr/src/app/node_modules/@nestjs/websockets/context/ws-context-creator.js:41:17
thing_api | at async AppGateway.<anonymous> (/usr/src/app/node_modules/@nestjs/websockets/context/ws-proxy.js:11:32)
thing_api | at async WebSocketsController.pickResult (/usr/src/app/node_modules/@nestjs/websockets/web-sockets-controller.js:85:24)
However, if I use the same DTO and validation pipe in regular controller, it works like a charm - with malformed payload I get properly formatted error message. Can somebody point out what I'm doing wrong?