NestJS循环内抛出HttpException无法返回响应的问题
问题:forEach循环中抛出的HttpException无法被Nest捕获返回响应
原代码实现
消息发送函数
async sendMessage(data: MessageDto, userId: string) { data.targets.forEach(async (channel) => { let gateway = await this.getUserChannel(userId, channel.channelId); switch (channel.target) { case 'Telegram': this.telegramService.sendMessageGateway(gateway, data) break; default: break; } }); }
获取用户通道函数
async getUserChannel(userId: string, channelId: string): Promise<IGateway> { const currentChannel = await this.GatewayModel.findOne({ userId: userId, channel.channelId }) if (!currentChannel) { throw new HttpException(`Gateway Not Found`, HttpStatus.NOT_FOUND); } return currentChannel; }
问题现象
getUserChannel抛出HttpException时,Nest无法将错误返回至响应;但在forEach循环外部调用该函数时,能正常返回404状态码响应。
解决后的代码
let datas = data.targets.map(async (channel) => { let gateway = await this.getUserChannel(userId, channel.channelId); switch (channel.target) { case 'Telegram': await this.telegramService.sendMessageGateway(gateway, data) break; default: break; } }) let allPromise = Promise.allSettled(datas) const statuses = await allPromise; console.log(statuses)
说明
此方案可供其他开发者参考。
内容的提问来源于stack exchange,提问作者monkeyUser
相关产品推荐
相关产品推荐

