# pydantic.errors.UnionError: 无法为联合类型验证输入

- **ID:** `python/pydantic-union-type-validation`
- **领域:** python
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

当字段类型为 Union[A, B] 时，Pydantic 会按顺序尝试每种类型；如果都不匹配，就会抛出 UnionError，通常是由于类型歧义或严格验证。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 2.x | active | — | — |

## 解决方案

1. **** (90% 成功率)
   ```
   Use discriminated unions with Literal types: Field(discriminator='type')
   ```
2. **** (85% 成功率)
   ```
   Define a custom validator to handle complex union logic
   ```

## 无效尝试

- **** — Order matters; if first type accepts too broadly, it may consume valid inputs for second type. (70% 失败率)
- **** — Optional[Union] can still fail if input is None but not allowed. (60% 失败率)
