서버가 자꾸 죽는다..?

현재

nestJS 웹소켓 게이트웨이에서 비정상적인 연결을 막기 위해

사용자가 소켓연결을 할 때 connectionId를 확인 → redis 확인 → 등록되어 있지 않다면 WsException을 던지고 있었다.

글로벌 필터를 적용해도 서버가 계속 죽는다…?

import { ArgumentsHost, Catch, Logger } from '@nestjs/common';
import { BaseWsExceptionFilter } from '@nestjs/websockets';

@Catch()
export class WsExceptionFilter extends BaseWsExceptionFilter {
  private readonly logger = new Logger('WsExceptionFilter');

  catch(exception: any, host: ArgumentsHost): void {
    const client = host.switchToWs().getClient();
    const error = exception.getError?.() || exception.message || exception;

    const errorResponse = {
      status: 'error',
      message: typeof error === 'object' ? JSON.stringify(error) : error,
      timestamp: new Date().toISOString(),
    };

    this.logger.error(`WebSocket Error: ${JSON.stringify(errorResponse)}`);
    this.logger.error(`Stack: ${exception.stack}`);

    client.emit('error', errorResponse);

    return;
  }
}

소켓서버에서의 모든 에러는 WsException을 상속한 커스텀 에러로 던지고 있었고, @Catch()에 WsExceoption을 넣어도, 안넣어도 에러가 잡히지 않고 죽는 경우가 있었다.

피어세션에서의 조언

→ 소켓통신에서의 필터는 main.ts가 아닌 해당 게이트웨이에 적용을 해야 에러가 잡힌다는 조언을 듣고 게이트웨이에 @UseFilters()로 필터를 적용

그래도 서버가 죽는다….?

원인은 handleConnection에서 사용자가 연결할 때 바로 joinRoom 메서드를 실행하고 있었는데 handleConnection은 핸드셰이킹 과정이여서

여기서 발생한 WsException은 WsExceptionFilter가 잡지 못하고 있었다.

handleConnetion에서 나는 에러는 try/catch로 꼭 잡아주자.