go
network_error
ai_generated
true
error: context 已取消
error: context canceled
ID: go/context-canceled-unexpected
80%修复率
87%置信度
0证据数
2024-05-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.19 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
在 goroutine 或 HTTP/数据库调用仍在使用 context 时,context 被取消(通过 cancel() 或父级取消),导致操作以 context.Canceled 失败。
English
A context was canceled (via cancel() or parent cancellation) while a goroutine or HTTP/database call was still using it, causing the operation to fail with context.Canceled.
解决方案
-
93% 成功率
if err := doWork(ctx); err != nil { if errors.Is(err, context.Canceled) { return nil // graceful shutdown } return err } -
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 } }
无效尝试
常见但无效的做法:
-
90% 失败
If the context is canceled, the retry uses the same canceled context and fails instantly, creating a tight loop.
-
85% 失败
Loses timeout and cancellation propagation, causing goroutine and connection leaks.