如何通过NestJS拦截器根据请求内容忽略请求并返回200
问题
当请求负载中的特定键满足条件时,如何返回状态码200并终止控制器调用?我在NestJS应用中使用Interceptors,但目前只能通过抛出异常的方式返回200状态码,想找一种更合理的实现方式。示例代码如下:
@Injectable() export class MyInterceptor implements NestInterceptor { intercept( context: ExecutionContext, next: CallHandler<any>, ): Observable<any> | Promise<Observable<any>> { const { data } = context.switchToHttp().getRequest().body as Message; const payload: InputData = JSON.parse(data.toString()); if (payload.order.payment.type === 'MY_SPECIFIC_VALUE') { // 如何在这里返回成功响应并终止控制器调用? throw new HttpException( { message: 'payment type is not supported, this message will be ignored.', }, 200, ); } return next.handle(); } }
解决方案
不需要通过抛出异常实现,直接通过ExecutionContext获取响应对象,设置状态码后返回包含响应体的Observable,即可终止后续控制器逻辑执行:
- 从
context中获取HTTP响应对象,设置状态码为200 - 用
of()创建Observable传入响应体,作为接口返回结果 - 不调用
next.handle(),跳过后续控制器方法执行
修改后的代码如下:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, of } from 'rxjs'; @Injectable() export class MyInterceptor implements NestInterceptor { intercept( context: ExecutionContext, next: CallHandler<any>, ): Observable<any> { const { data } = context.switchToHttp().getRequest().body as Message; const payload: InputData = JSON.parse(data.toString()); if (payload.order.payment.type === 'MY_SPECIFIC_VALUE') { // 获取响应对象并设置状态码 const response = context.switchToHttp().getResponse(); response.status(200); // 返回响应体,终止控制器调用 return of({ message: 'payment type is not supported, this message will be ignored.', }); } return next.handle(); } }
说明
response.status(200)明确标记响应为成功状态,符合HTTP语义of()创建的Observable会立即发出指定响应体,Nest会直接将其作为接口返回内容- 跳过
next.handle()调用后,拦截器直接截断请求流程,控制器方法不会被执行
内容的提问来源于stack exchange,提问作者Rafa Acioly
相关产品推荐
相关产品推荐

