go network_error ai_generated true

rpc 错误:code = Canceled desc = 上下文已取消

rpc error: code = Canceled desc = context canceled

ID: go/grpc-context-canceled-client

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

版本兼容性

版本状态引入弃用备注
google.golang.org/grpc v1.50+ active — — —

根因分析

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

English

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

generic

解决方案

  1. 90% 成功率
    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% 成功率
    for {
        select {
        case <-ctx.Done():
            return nil, status.FromContextError(ctx.Err()).Err()
        default:
            // do work
        }
    }

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 85% 失败

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