go network_error ai_generated true

error: context canceled

ID: go/context-canceled-unexpected

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-05-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.19 active
1.21 active

Root Cause

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.

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 90% fail

    If the context is canceled, the retry uses the same canceled context and fails instantly, creating a tight loop.

  2. 85% fail

    Loses timeout and cancellation propagation, causing goroutine and connection leaks.