NestJS 拦截器 - 如何在响应结束后获取响应状态码
NestJS Interceptor - how to get response status code after response is end
在拦截器中,我可以通过 context.getArgByIndex(1)
获取响应状态。此代码记录了我想要的 403 状态代码。但是这段代码 context.getArgByIndex(1).statusCode
return 对我来说是状态 201。我从服务中丢弃了状态 403。
拦截器代码
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()
}
}
为测试抛出错误的服务代码
async findAll(): Promise<PodsDto[]> {
throw new ForbiddenException()
return this.PodsRepository.find()
}
也许不是一个好的选择,但它确实有效。
拦截器代码
@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()
}
}
在拦截器中,我可以通过 context.getArgByIndex(1)
获取响应状态。此代码记录了我想要的 403 状态代码。但是这段代码 context.getArgByIndex(1).statusCode
return 对我来说是状态 201。我从服务中丢弃了状态 403。
拦截器代码
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()
}
}
为测试抛出错误的服务代码
async findAll(): Promise<PodsDto[]> {
throw new ForbiddenException()
return this.PodsRepository.find()
}
也许不是一个好的选择,但它确实有效。
拦截器代码
@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()
}
}