You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 00:25:22