go network_error ai_generated true

错误:上下文已超过截止时间(来自 select ctx.Done())

error: context deadline exceeded (from select ctx.Done())

ID: go/context-deadline-exceeded-in-select

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

版本兼容性

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

根因分析

select 语句观察到 ctx.Done(),因为父上下文的截止时间已到。下游操作被取消,但调用方将其视为通用错误。

English

A select statement observes ctx.Done() because the parent context's deadline elapsed. The downstream operation is cancelled, but the caller treats it as a generic error.

generic

解决方案

  1. 96% 成功率
    select {
    case <-ctx.Done():
        return ctx.Err()
    case res := <-ch:
        return res
    }
  2. 90% 成功率
    for i := 0; i < 3; i++ {
        ctx, cancel := context.WithTimeout(parent, 2*time.Second)
        err := call(ctx)
        cancel()
        if err == nil { return nil }
    }

无效尝试

常见但无效的做法:

  1. 95% 失败

    The deadline is fixed; every retry burns the same expired context and returns instantly.

  2. 90% 失败

    Callers receive silently wrong results and downstream logic corrupts data.