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

如何通过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,即可终止后续控制器逻辑执行:

  1. 从context中获取HTTP响应对象,设置状态码为200
  2. 用of()创建Observable传入响应体,作为接口返回结果
  3. 不调用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 01:12:39