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

NestJS服务抛出异常导致服务崩溃的问题求助

问题描述

想在NestJS的Service中抛出异常,在Controller中处理后向前端返回JSON格式的错误信息,但实际触发异常时,NestJS服务器直接崩溃,而非返回预期的404响应。

代码实现

GeneratorController

@ApiTags('Generator')
@Controller({
  path: 'api/generator',
  version: '1',
})
export class GeneratorController {
  private readonly logger = new Logger(GeneratorController.name);
  constructor(private tractionUnitService: TractionUnitGeneratorService) {}
  
  @Get('batch/preview')
  @ApiResponse({
    status: 200,
    description: 'Sucessfuly get batch preview',
  })
  @ApiResponse({
    status: 404,
    description: 'Error your batch number is not found',
  })
  async batchPreview(@Query('batchNumber') batchNumber: number): Promise<GenerationBatch> {
    try{
      return batch = this.tractionUnitService.getBatch(batchNumber);
    }catch(e){
      this.logger.error(e)
      throw e;
    }
  } 
}

TractionUnitGeneratorService

@Injectable()
export class TractionUnitGeneratorService {

  public async getBatch(batchNumber: number): Promise<GenerationBatch> {
    const batchs = (await this.getBatchs()).value.filter((bat) => bat.batchNumber == batchNumber);
    if (batchs.length == 1) {
      return batchs[0];
    } else {
      throw new NotFoundException(`Batch n°${batchNumber} not found`);
    }
 }
}
错误日志
C:\Users\mrsolarius\Documents\Projets\****\back\src\generator\traction-unit-generator\traction-unit-generator.service.ts:75
      throw new NotFoundException({
            ^
NotFoundException: Batch n°1 not found
    at TractionUnitGeneratorService.getBatch (C:\Users\mrsolarius\Documents\Projets\****\back\src\generator\traction-unit-generator\traction-unit-generator.service.ts:75:13)
    at GeneratorControlerController.batchPreview (C:\Users\mrsolarius\Documents\Projets\****\back\src\controllers\generator\generator.controller.ts:105:32)
    at C:\Users\mrsolarius\Documents\Projets\****\back\node_modules\@nestjs\core\router\router-execution-context.js:38:29
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at C:\Users\mrsolarius\Documents\Projets\****\back\node_modules\@nestjs\core\router\router-execution-context.js:46:28
    at C:\Users\mrsolarius\Documents\Projets\****\back\node_modules\@nestjs\core\router\router-proxy.js:9:17
环境信息
[System Information]
OS Version     : Windows 10
NodeJS Version : v16.15.0
NPM Version    : 8.5.5 

[Nest CLI]
Nest CLI Version : 9.0.0

[Nest Platform Information]
platform-express version : 9.0.1
schematics version       : 9.0.1
swagger version          : 6.0.1
testing version          : 9.0.1
common version           : 9.0.1
axios version            : 0.1.0
core version             : 9.0.1
cli version              : 9.0.0
解决方案

服务器崩溃的核心原因是异步方法未使用await调用,导致try/catch无法捕获Service抛出的异步异常,最终异常冒泡到Nest的顶层未被处理。具体修复点:

  • 添加await调用异步方法:
    Service的getBatch是异步方法,Controller中调用时必须加await,否则返回的是Promise对象,且异步异常无法被当前try/catch捕获。

  • 修复变量声明问题:
    原代码中return batch = ...的写法存在未声明变量的问题,应直接返回await后的结果,或先声明变量再赋值。

修复后的Controller代码:

@ApiTags('Generator')
@Controller({
  path: 'api/generator',
  version: '1',
})
export class GeneratorController {
  private readonly logger = new Logger(GeneratorController.name);
  constructor(private tractionUnitService: TractionUnitGeneratorService) {}
  
  @Get('batch/preview')
  @ApiResponse({
    status: 200,
    description: 'Sucessfuly get batch preview',
  })
  @ApiResponse({
    status: 404,
    description: 'Error your batch number is not found',
  })
  async batchPreview(@Query('batchNumber') batchNumber: number): Promise<GenerationBatch> {
    try{
      // 添加await,并修复变量问题
      return await this.tractionUnitService.getBatch(batchNumber);
    }catch(e){
      this.logger.error(e)
      throw e;
    }
  } 
}

额外说明:NestJS自带的全局异常过滤器会自动处理所有继承自HttpException的异常(包括NotFoundException),即使去掉Controller中的try/catch,只要正确await异步方法,框架会自动返回对应的JSON错误响应(包含状态码和错误信息)。如果仅需要日志记录,保留try/catch并重新抛出异常即可。

内容的提问来源于stack exchange,提问作者MrSolarius

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:54:17