# GraphQL 错误：不能为非空字段返回 null

- **ID:** `api/graphql-non-null-field-returned-null`
- **领域:** api
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 82%

## 根因

解析器为 GraphQL 模式中标记为非空 (!) 的字段返回了 null，导致父字段也变为 null（null 传播）。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| graphql-js 16.8.0 | active | — | — |
| Apollo Server 4.9.0 | active | — | — |
| GraphQL Ruby 2.3.0 | active | — | — |
| HotChocolate 13.8.0 | active | — | — |

## 解决方案

1. ```
   Identify the failing field from the error path (e.g., 'user.profile.name') and fix the resolver to return a valid value. Example: ensure the database query joins the required table or adds a fallback like `name: user.name || 'Unknown'`.
   ```
2. ```
   Temporarily make the field nullable in the schema (change `!` to `?` in SDL) to prevent null propagation while debugging the resolver.
   ```
3. ```
   Add error handling in the resolver to log the null case and return a sensible default. For example, in JavaScript: `const name = user?.profile?.name ?? 'Anonymous';`.
   ```

## 无效尝试

- **** — Clients may not handle null gracefully, leading to runtime errors or missing data. (70% 失败率)
- **** — Default values can hide data integrity problems and produce incorrect results. (60% 失败率)
- **** — Returning null from a non-null field still triggers the same error, as GraphQL validates at the schema level. (80% 失败率)
