# error: context 已取消

- **ID:** `go/context-canceled-unexpected`
- **领域:** go
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在 goroutine 或 HTTP/数据库调用仍在使用 context 时，context 被取消（通过 cancel() 或父级取消），导致操作以 context.Canceled 失败。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.19 | active | — | — |
| 1.21 | active | — | — |

## 解决方案

1. **** (93% 成功率)
   ```
   if err := doWork(ctx); err != nil {
    if errors.Is(err, context.Canceled) {
        return nil // graceful shutdown
    }
    return err
}
   ```
2. **** (88% 成功率)
   ```
   for i := 0; i < 3; i++ {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    err := call(ctx)
    cancel()
    if err == nil { return nil }
}
   ```

## 无效尝试

- **** — If the context is canceled, the retry uses the same canceled context and fails instantly, creating a tight loop. (90% 失败率)
- **** — Loses timeout and cancellation propagation, causing goroutine and connection leaks. (85% 失败率)
