go runtime_error ai_generated true

error: context 已取消

error: context canceled

ID: go/context-canceled-propagated

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-09-04首次发现

版本兼容性

版本状态引入弃用备注
1.21+ active — — —

根因分析

父 context 被取消(或超时),子操作返回 context.Canceled。常见原因是过早 defer cancel(),或把请求 context 复用到后台任务。

English

A parent context was canceled (or timed out) and child operations returned context.Canceled. Often caused by deferring cancel() too early or sharing a request context across background work.

generic

解决方案

  1. 90% 成功率
    bg := context.WithoutCancel(ctx)
    go func() { longRunning(bg) }()
  2. 92% 成功率
    if errors.Is(err, context.Canceled) {
        return nil // expected shutdown
    }

无效尝试

常见但无效的做法:

  1. 60% 失败

    Hides real shutdown bugs and leaks resources; also masks timeout-induced failures.

  2. 70% 失败

    Breaks request cancellation and leaks goroutines after client disconnect.