如何为适配器@nestjs/platform-ws的nestjs websocket发送exception/error

how to send the exception/error for nestjs websocket of adapter @nestjs/platform-ws

我正在尝试根据条件使用 nestjs websocket 发送异常,尝试使用

抛出新的 WsException('Invalid data');

但没有发送任何异常

这里是示例代码

import WebSocket from 'ws';
import {
  SubscribeMessage,
  WebSocketGateway,
  WsException,
} from '@nestjs/websockets';

@WebSocketGateway({ path: '/api' })
export class MainGateway {
  @SubscribeMessage('message')
  handleMessage(client: WebSocket, payload: any) {
    if (payload.id === 4) {
      throw new WsException('Invalid Data');
    }
    client.send(JSON.stringify({ id: payload.id }));
  }
}

我正在使用 angular 创建连接,这里是代码片段

export class WsComponent implements OnInit {
  public value!: number;
  public subject$ = webSocket('ws://localhost:3000/api');

  ngOnInit(): void {
    const event = { event: 'message', data: { id: 4 } };

    this.subject$.subscribe({
      next: (v: any) => (this.value = v.id),
      error: (e) => console.error(e),
      complete: () => console.info('complete'),
    });

    this.subject$.next(event);
  }
}

请帮我解决问题

我一直在为同样的问题而苦苦挣扎。我认为问题在于 BaseWsExceptionFilter 及其对 soket.emit 的用法。我想出了以下内容:

import { ArgumentsHost, Catch, HttpException } from "@nestjs/common";
import { BaseWsExceptionFilter, WsException } from "@nestjs/websockets";

@Catch(WsException, HttpException)
export class WebsocketExceptionsFilter extends BaseWsExceptionFilter {
  catch(exception: WsException | HttpException, host: ArgumentsHost) {
    const client = host.switchToWs().getClient() as WebSocket;
    const data = host.switchToWs().getData();
    const error = exception instanceof WsException ? exception.getError() : exception.getResponse();
    const details = error instanceof Object ? { ...error } : { message: error };
    client.send(JSON.stringify({
      event: "error",
      data: {
        id: (client as any).id,
        rid: data.rid,
        ...details
      }
    }));
  }
}

很确定 extends BaseWsExceptionFilter 是多余的,因为我没有使用任何 class。然后我将它应用到我的网关:

@WebSocketGateway()
@UseFilters(WebsocketExceptionsFilter)
@UsePipes(new ValidationPipe({ transform: true }))
export class FeedGateway implements OnGatewayConnection, OnGatewayDisconnect {
}

这帮助我收到以下错误:

{"event":"error","data":{"id":"7a784ce568767a1016090c6a","rid":"connect","statusCode":400,"message":["language must be a valid enum value"],"error":"Bad Request"}}