NestJS Interceptor – how to get response status code after response is end

Issue

In interceptor i can get response status by context.getArgByIndex(1). This code logs a 403 status code as i wanted. But this code context.getArgByIndex(1).statusCode return to me status 201. I throw out status 403 from the service.

Interceptor code

import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import { LogsService } from './logs.service';

@Injectable()
export class LogsInterceptor implements NestInterceptor {
  constructor( private readonly logService: LogsService ) {}
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    
    
    this.logService.constructorData(context)

    console.log(context.getArgByIndex(0)) --- **This code logs the correct status**
    console.log(context.getArgByIndex(0).statusCode) --- **This code logs status 201**

    return next.handle()    
  }
}

Service code that throws an error for the test

async findAll(): Promise<PodsDto[]> {
     throw new ForbiddenException()
     return this.PodsRepository.find()
}

Solution

Maybe a not good option, but it works.

Interceptor code

@Injectable()
export class LogsInterceptor implements NestInterceptor {
  constructor( private readonly logService: LogsService ) {}
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    
    const ctx = context.switchToHttp();
    const response = ctx.getResponse();

    response.on('close', ()=>{
      this.logService.constructorData(context)
    })

    return next.handle()
  }
}

Answered By – Shem

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.