MrSolarius
MrSolarius

Reputation: 799

NestJs crash when I throw error in my service

I want to throw an exception in my service and handle it in my controller to inform the front end of the error.

To achieve that, I have created a controller and a service that looks like that :

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`);
    }
 }
}

I except the application to return a JSON with not found exception, like when it's done in controller. But I get a fatal exception instead that stop completely the NestJs server.

Here is the message :

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

My nest info :

[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

Upvotes: 6

Views: 7078

Answers (1)

MrSolarius
MrSolarius

Reputation: 799

My mistake here was to not wait for my asynchronous request to throw the error. That mean each error throws wasn't catch so the application crash.

Two solutions here :

The simple one is to use .catch((e)=>console.error(e)) and not return any value to the frontend

The second possibility is to add await in front of the request call and the error throw will be caught.

Upvotes: 15

Related Questions