websocket 未捕获Mikro ORM验证错误

hc8w905p  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(228)

我有以下功能:

@SubscribeMessage('sendMessage')
  async handleSendMessage(
    _: Socket,
    payload: CreateMessageInput,
  ): Promise<void> {
    try {
      const created = this.em.create(Chat, {
        text: payload.text,
        user: payload.userId,
      });
      this.em.persistAndFlush(created);

      const { userName } = await this.em.findOneOrFail(User, {
        id: payload.userId,
      });

      this.server.emit('receiveMessage', {
        text: payload.text,
        user: { userName, id: payload.userId },
      });
    } catch (e) {
      if (e.name === 'NotFoundError') {
        throw new NotFoundException('User not found.');
      }
      throw new InternalServerErrorException('Something went wrong');
    }
  }

如果我在测试这个函数时忽略了user,我得到了ValidationError: Value for Chat.user is required, 'undefined' found,但是这个错误没有被我的catch子句捕获,导致套接字挂起。我该怎么解决这个问题?

zi8p0yeb

zi8p0yeb1#

你错过了一个等待:

const created = this.em.create(Chat, {
  text: payload.text,
  user: payload.userId,
});
await this.em.persistAndFlush(created); // <--

还要注意,您不必持久化通过em.create创建的实体,这在当前版本中会自动发生,因此在这里调用em.flush()就足够了。

相关问题