nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.69k stars 7.63k forks source link

BaseExceptionFilter provider for WebSocket using WS doesn't send error messages to client #11433

Closed dieeisenefaust closed 1 year ago

dieeisenefaust commented 1 year ago

Is there an existing issue for this?

Current behavior

``I have spent pretty extensive time looking for an answer to this situation and the very few instances I found where it was mentioned failed to address the primary issue or provide a clear answer.

When running a WebSocket gateway using the WS platform and using the BaseWsExceptionFilter to catch validation errors thrown by the ValidationPipe provider applied to the gateway, the error is logged to the console on the server side but nothing is sent to the client.

I believe this may be due to the fact that the BaseWsExceptionFilter uses client.emit('exception', message) which, I believe, is Socket.io specific.

Gateway code:

@UsePipes(new ValidationPipe({ transform: true, enableDebugMessages: true }))
@WebSocketGateway({
  cors: {
    origin: '*',
  },
  //path: '/test',
})
export class TimespanGateway {
  @WebSocketServer() server: Server;

  constructor(private readonly timespanService: TimespanService) {}

  @SubscribeMessage('createTimespan')
  //@UseFilters(new AllExceptionsFilter())
  @UseFilters(new BaseWsExceptionFilter())
  async create(
    @MessageBody() createTimespanDto: CreateTimespanDto,
  ): Promise<{ Message: string; createTimespanDto: CreateTimespanDto }> {
    //return this.timespanService.create(createTimespanDto);
    this.server.emit(JSON.stringify({ message: 'test', createTimespanDto }));
    return { Message: 'From Create', createTimespanDto };
  }

Error captured on server:

[Nest] 7877  - 04/06/2023, 12:31:33 AM   ERROR [WsExceptionsHandler] Bad Request Exception
BadRequestException: Bad Request Exception
    at ValidationPipe.exceptionFactory (/root/fbpTest/janus-ws/node_modules/@nestjs/common/pipes/validation.pipe.js:99:20)
    at ValidationPipe.transform (/root/fbpTest/janus-ws/node_modules/@nestjs/common/pipes/validation.pipe.js:72:30)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at resolveParamValue (/root/fbpTest/janus-ws/node_modules/@nestjs/websockets/context/ws-context-creator.js:105:31)
    at async Promise.all (index 0)
    at pipesFn (/root/fbpTest/janus-ws/node_modules/@nestjs/websockets/context/ws-context-creator.js:107:13)
    at /root/fbpTest/janus-ws/node_modules/@nestjs/websockets/context/ws-context-creator.js:42:17
    at TimespanGateway.<anonymous> (/root/fbpTest/janus-ws/node_modules/@nestjs/websockets/context/ws-proxy.js:11:32)
    at WebSocketsController.pickResult (/root/fbpTest/janus-ws/node_modules/@nestjs/websockets/web-sockets-controller.js:96:24)

Minimum reproduction code

https://github.com/dieeisenefaust/janus-ws

Steps to reproduce

npm run build npm run start

either use something like Browser WebSocket Client (a Chrome extensions) and/or a HTML client like 'clienttest.html' in the root of the repo provided.

The validation pipe is enforcing the IsNotEmpty class-validator decorators in the create-timespan.dto.ts file. So any message should include userId, location, job and task.

Sending a payload without userId will trigger an exception.

{
  "event": "createTimespan",
  "data": {
         "location": "Egypt",
         "job": "Archeologist",
         "task": "dig"
      }
}

The exception will only show in console.log within your code editor running the server.

Expected behavior

Expect an error to be returned to the client.

Package

Other package

No response

NestJS version

9.3.0

Packages versions

  "dependencies": {
    "@nestjs/common": "^9.0.0",
    "@nestjs/core": "^9.0.0",
    "@nestjs/mapped-types": "*",
    "@nestjs/platform-express": "^9.0.0",
    "@nestjs/platform-ws": "^9.3.12",
    "@nestjs/websockets": "^9.3.12",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.14.0",
    "reflect-metadata": "^0.1.13",
    "rxjs": "^7.2.0",
    "ws": "^8.13.0"
  }

Node.js version

18.14.2

In which operating systems have you tested?

Other

No response

kamilmysliwiec commented 1 year ago

Duplicate https://github.com/nestjs/nest/issues/9056