socket-controllers icon indicating copy to clipboard operation
socket-controllers copied to clipboard

fix: Non-JSON message from client causes uncaught ParameterParseJsonError error

Open abourdin opened this issue 4 years ago • 0 comments

Description

When sending a message that isn't proper JSON to a socket controller expecting a @MessageBody(), server throws an uncaught exception.

Minimal code-snippet showcasing the problem

@SocketController('/chat')
export default class ChatSocketController {
  @OnConnect()
  public connection(@ConnectedSocket() socket: any) {
    logger.info('client connected');
  }

  @OnDisconnect()
  public disconnect(@ConnectedSocket() socket: any) {
    logger.info('client disconnected');
  }

  @OnMessage('send_message')
  @EmitOnFail('send_message_error')
  public save(@ConnectedSocket() socket: any, @MessageBody() message: any) {
    logger.info('received message:', message);
    socket.emit('message_received', message);
  }
}

Expected behavior

I would expect that either socket-controllers provides a way to gracefully handle this error (similar to an error handling middleware), or that this exception is simply logged and triggers the @EmitOnFail() decorator, instead of being uncaught.

Actual behavior

Following uncaught exception is thrown:

Error: 
    at new ParameterParseJsonError (/myproject/src/error/ParameterParseJsonError.ts:9:22)
    at SocketControllerExecutor.parseParamValue (/myproject/src/SocketControllerExecutor.ts:227:19)
    at SocketControllerExecutor.handleParamFormat (/myproject/src/SocketControllerExecutor.ts:212:34)
    at SocketControllerExecutor.handleParam (/myproject/src/SocketControllerExecutor.ts:181:26)
    at /myproject/src/SocketControllerExecutor.ts:163:33
    at Array.map (<anonymous>)
    at SocketControllerExecutor.handleAction (/myproject/src/SocketControllerExecutor.ts:136:14)
    at Socket.<anonymous> (/myproject/src/SocketControllerExecutor.ts:122:30)
    at Socket.emit (events.js:315:20)
    at Socket.EventEmitter.emit (domain.js:482:12)
    at /myproject/node_modules/socket.io/lib/socket.js:528:12
    at processTicksAndRejections (internal/process/task_queues.js:79:11)
[ERROR] 10:45:15 ParameterParseJsonError: Parameter is invalid. Value ("test") cannot be parsed to JSON

This uncaught exception that rises to the process level has the effect of crashing the entire express server.

abourdin avatar Sep 22 '20 08:09 abourdin