go runtime_error ai_generated true

rpc error: code = Canceled desc = context canceled

ID: go/grpc-canceled-context-cancelled

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2025-03-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.1 active

Root Cause

The client cancelled the context before the RPC completed, often due to user action or timeout.

generic

中文

客户端在RPC完成之前取消了上下文,通常是由于用户操作或超时。

Workarounds

  1. 90% success Create a new context for each RPC call to avoid using cancelled contexts.
    ctx := context.Background()
    resp, err := client.SomeRPC(ctx, req)
    if err != nil {
        if status.Code(err) == codes.Canceled {
            // Create new context and retry if appropriate
            ctx2 := context.Background()
            resp, err = client.SomeRPC(ctx2, req)
        }
    }
  2. 85% success Handle cancellation gracefully by checking context errors.
    select {
    case <-ctx.Done():
        return nil, ctx.Err()
    default:
    }
    resp, err := client.SomeRPC(ctx, req)

Dead Ends

Common approaches that don't work:

  1. Ignore the cancellation and retry with the same context. 100% fail

    The cancelled context cannot be reused; a new context is needed.

  2. Remove context cancellation logic entirely. 90% fail

    This can lead to resource leaks and unresponsive applications.