GraphQL 查询错误与 HTTP 错误有何不同?NestJS 如何统一返回 GraphQL 错误格式?
解读
国内面试官问这道题,想确认三件事:
- 候选人是否真正在生产环境用过 GraphQL,而不是只写过 Demo;
- 是否理解 GraphQL「以 200 承载业务异常」的协议本质;
- 能否在 NestJS 体系里把「异常→错误格式」做成可配置、可追踪、对前端友好的一次性方案,而不是每个 resolver 手写 try/catch。
回答时要突出「协议差异 → NestJS 异常过滤器 → 自定义错误对象 → 日志/监控对接」这一完整闭环,让面试官听到“企业级落地”四个字。
知识点
- HTTP 错误:状态码 4xx/5xx 直接反映通信层结果,body 可任意,无强制规范。
- GraphQL 错误:协议层永远返回 200,错误放在
errors[]数组,单条错误含message、extensions、locations、path四段;extensions是扩展主战场,国内团队常用来放code、timestamp、requestId、debugStack等。 - NestJS 异常层次:
• 基类HttpException(REST 用)
• 子类GraphQLError(apollo-server-express提供)
• 过滤器层级:BaseExceptionFilter→CustomExceptionFilter;GraphQL 侧对应ExceptionFilter且需标记@Catch()。 - 统一格式手段:
• 自定义ValidationError/BusinessError领域异常;
• 在过滤器里把任意异常映射成标准GraphQLFormattedError;
• 利用formatError钩子对 ApolloDriver 做最后一次加工,保证日志、Sentry、SkyWalking 拿到的是同一对象。 - 国内合规要求:生产环境
debugStack必须按环境变量开关,防止源码泄露。
答案
一、差异对比
- 通信层:HTTP 错误用状态码表达结果,GraphQL 无论成败均返回 200,错误信息在 body 的
errors数组。 - 格式:HTTP body 可自定义;GraphQL 单条错误必须包含
message,可选extensions/locations/path。 - 请求粒度:HTTP 一失败整请求挂掉;GraphQL 允许部分字段成功、部分字段失败,因此
errors是数组。
二、NestJS 统一方案(生产级步骤)
- 定义领域异常
export class BizException extends HttpException {
constructor(public code: string, message: string, status = 400) {
super({ code, message }, status);
}
}
- 写 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 }),
},
};
}
}
- 全局注册
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: 'schema.gql',
formatError: (error: GraphQLFormattedError) => error, // 可再加工
context: ({ req }) => ({ req }),
}),
app.useGlobalFilters(new GraphQLExceptionFilter());
- 在 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;
}
- 前端拿到
{
"errors": [{
"message": "用户不存在",
"extensions": {
"code": "USER_NOT_FOUND",
"timestamp": "2024-06-01T12:00:00.000Z",
"requestId": "a1b2c3d4"
}
}]
}
- 日志与监控:在过滤器同一处把
extensions原样写进 winston / Sentry,保证排障时requestId可追踪。
拓展思考
- 多协议共存:同一个应用同时暴露 REST 与 GraphQL 时,可把异常抽象成
AppError,再分别派生HttpExceptionFilter与GraphQLExceptionFilter,做到“业务语义不变,传输层适配”。 - 错误码规范:国内大厂普遍采用 3 位主分类 + 3 位子码(如 A01001),在
extensions.code里返回,方便前端做国际化映射。 - 批量错误:GraphQL 支持返回
UserError[],可在一次 mutation 里回传多个字段级校验失败;NestJS 通过class-validator的validateSync把ValidationError转成数组,再抛自定义ValidationListException即可。 - 性能陷阱:过滤器里不要同步解析整个
stack,可异步上报,防止高并发时阻塞事件循环。 - 合规安全:toB 项目交付银行或车企时,
extensions里的debugStack必须可开关,且通过配置中心热更新,满足监管现场巡检要求。