go network_error ai_generated true

rpc error: code = Canceled desc = context canceled

ID: go/grpc-context-canceled-client

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
google.golang.org/grpc v1.50+ active — — —

Root Cause

The client canceled the context (e.g., HTTP request aborted, timeout on parent ctx, or explicit cancel()) before the RPC completed.

generic

中文

客户端在 RPC 完成前取消了上下文(例如 HTTP 请求中止、父 ctx 超时或显式调用 cancel())。

Workarounds

  1. 90% success
    resp, err := client.Get(ctx, req)
    if err != nil {
        if errors.Is(ctx.Err(), context.Canceled) {
            log.Printf("caller canceled: %v", ctx.Err())
            return nil, err
        }
        if status.Code(err) == codes.Canceled {
            return nil, status.Error(codes.Canceled, "server canceled RPC")
        }
        return nil, err
    }
  2. 88% success
    for {
        select {
        case <-ctx.Done():
            return nil, status.FromContextError(ctx.Err()).Err()
        default:
            // do work
        }
    }

Dead Ends

Common approaches that don't work:

  1. 90% fail

    If the caller canceled, the retry will also be canceled immediately — wasted work.

  2. 85% fail

    Loses parent deadline/cancellation propagation; goroutines leak on client disconnect.