GraphQL 查询错误与 HTTP 错误有何不同?NestJS 如何统一返回 GraphQL 错误格式?

解读

国内面试官问这道题,想确认三件事:

  1. 候选人是否真正在生产环境用过 GraphQL,而不是只写过 Demo;
  2. 是否理解 GraphQL「以 200 承载业务异常」的协议本质;
  3. 能否在 NestJS 体系里把「异常→错误格式」做成可配置、可追踪、对前端友好的一次性方案,而不是每个 resolver 手写 try/catch。

回答时要突出「协议差异 → NestJS 异常过滤器 → 自定义错误对象 → 日志/监控对接」这一完整闭环,让面试官听到“企业级落地”四个字。

知识点

  1. HTTP 错误:状态码 4xx/5xx 直接反映通信层结果,body 可任意,无强制规范。
  2. GraphQL 错误:协议层永远返回 200,错误放在 errors[] 数组,单条错误含 message、extensions、locations、path 四段;extensions 是扩展主战场,国内团队常用来放 code、timestamp、requestId、debugStack 等。
  3. NestJS 异常层次:
    • 基类 HttpException(REST 用)
    • 子类 GraphQLError(apollo-server-express 提供)
    • 过滤器层级:BaseExceptionFilter → CustomExceptionFilter;GraphQL 侧对应 ExceptionFilter 且需标记 @Catch()。
  4. 统一格式手段:
    • 自定义 ValidationError / BusinessError 领域异常;
    • 在过滤器里把任意异常映射成标准 GraphQLFormattedError;
    • 利用 formatError 钩子对 ApolloDriver 做最后一次加工,保证日志、Sentry、SkyWalking 拿到的是同一对象。
  5. 国内合规要求:生产环境 debugStack 必须按环境变量开关,防止源码泄露。

答案

一、差异对比

  1. 通信层:HTTP 错误用状态码表达结果,GraphQL 无论成败均返回 200,错误信息在 body 的 errors 数组。
  2. 格式:HTTP body 可自定义;GraphQL 单条错误必须包含 message,可选 extensions/locations/path。
  3. 请求粒度:HTTP 一失败整请求挂掉;GraphQL 允许部分字段成功、部分字段失败,因此 errors 是数组。

二、NestJS 统一方案(生产级步骤)

  1. 定义领域异常
export class BizException extends HttpException {
  constructor(public code: string, message: string, status = 400) {
    super({ code, message }, status);
  }
}
  1. 写 GraphQL 异常过滤器
@Catch()
export class GraphQLExceptionFilter implements GqlExceptionFilter {
  catch(exception: unknown): GraphQLFormattedError {
    let code = 'INTERNAL_ERROR';
    let message = '服务器开小差';
    let stack: string | undefined;

    if (exception instanceof BizException) {
      code = exception.code;
      message = exception.message;
    } else if (exception instanceof HttpException) {
      code = 'HTTP_ERROR';
      message = exception.message;
    } else if (exception instanceof Error) {
      message = exception.message;
      stack = exception.stack;
    }

    return {
      message,
      extensions: {
        code,
        timestamp: new Date().toISOString(),
        requestId: cls.get('requestId'), // 链路追踪
        ...(process.env.NODE_ENV !== 'production' && { stack }),
      },
    };
  }
}
  1. 全局注册
GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  autoSchemaFile: 'schema.gql',
  formatError: (error: GraphQLFormattedError) => error, // 可再加工
  context: ({ req }) => ({ req }),
}),
app.useGlobalFilters(new GraphQLExceptionFilter());
  1. 在 Resolver 里直接抛
@Query(() => User)
async user(@Args('id') id: string) {
  const exist = await this.userService.findOne(id);
  if (!exist) throw new BizException('USER_NOT_FOUND', '用户不存在');
  return exist;
}
  1. 前端拿到
{
  "errors": [{
    "message": "用户不存在",
    "extensions": {
      "code": "USER_NOT_FOUND",
      "timestamp": "2024-06-01T12:00:00.000Z",
      "requestId": "a1b2c3d4"
    }
  }]
}
  1. 日志与监控:在过滤器同一处把 extensions 原样写进 winston / Sentry,保证排障时 requestId 可追踪。

拓展思考

  1. 多协议共存:同一个应用同时暴露 REST 与 GraphQL 时,可把异常抽象成 AppError,再分别派生 HttpExceptionFilter 与 GraphQLExceptionFilter,做到“业务语义不变,传输层适配”。
  2. 错误码规范:国内大厂普遍采用 3 位主分类 + 3 位子码(如 A01001),在 extensions.code 里返回,方便前端做国际化映射。
  3. 批量错误:GraphQL 支持返回 UserError[],可在一次 mutation 里回传多个字段级校验失败;NestJS 通过 class-validator 的 validateSync 把 ValidationError 转成数组,再抛自定义 ValidationListException 即可。
  4. 性能陷阱:过滤器里不要同步解析整个 stack,可异步上报,防止高并发时阻塞事件循环。
  5. 合规安全:toB 项目交付银行或车企时,extensions 里的 debugStack 必须可开关,且通过配置中心热更新,满足监管现场巡检要求。