我有以下功能:
@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子句捕获,导致套接字挂起。我该怎么解决这个问题?
1条答案
按热度按时间zi8p0yeb1#
你错过了一个等待:
还要注意,您不必持久化通过
em.create
创建的实体,这在当前版本中会自动发生,因此在这里调用em.flush()
就足够了。