javascript 如何发送适配器@nestjs/platform-ws的nestjs WebSocket的异常/错误

bnlyeluc  于 2023-01-19  发布在  Java
关注(0)|答案(2)|浏览(222)

我尝试使用nestjs websocket基于条件发送异常,尝试使用

    • 抛出新的WsException("无效数据");**

但不发送任何异常
下面是示例代码

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);
  }
}

你帮我解决一下

l7mqbcuq

l7mqbcuq1#

我也遇到过同样的问题。我相信这个问题是与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是多余的,因为我没有使用该类的任何东西,然后我将它应用到我的网关:

@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"}}
dgsult0t

dgsult0t2#

运行正常,但需要更多测试。如果发现错误,请报告。

import { ArgumentsHost, Catch } from '@nestjs/common';
import { BaseWsExceptionFilter } from '@nestjs/websockets';
import { PacketType } from 'socket.io-parser';
@Catch()
export class AllExceptionsSocketFilter extends BaseWsExceptionFilter {
   catch(exception: any, host: ArgumentsHost) {
      const client = host.switchToWs().getClient();
      client.packet({
          type: PacketType.ACK,
          data: [{ error: exception?.message }],
          id: client.nsp._ids++,
      });
   }
}

use:

@WebSocketGateway()
@UseFilters(new AllExceptionsSocketFilter())
export class ContatoGateway {
   ...

相关问题