Search code examples
validationwebsocketsocket.ionestjsmikro-orm

Mikro ORM validation errors not catched


I have the following function:

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

If I omit the user when testing this function, Im getting ValidationError: Value for Chat.user is required, 'undefined' found , but this error is not being catched by my catch clause, resulting in the socket hanging. How can I fix this?


Solution

  • You are missing an await in there:

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

    Also note that you don't have to persist entities created via em.create, that happens automatically in current versions, so calling em.flush() is enough here.