# rpc错误：代码=已取消 描述=grpc：客户端连接正在关闭

- **ID:** `go/grpc-stream-interrupted-client-cancel`
- **领域:** go
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

gRPC客户端取消了上下文，导致流式RPC过早终止。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 1.1 | active | — | — |

## 解决方案

1. **Handle context cancellation gracefully and restart stream.** (90% 成功率)
   ```
   for {
    stream, err := client.StreamRPC(ctx)
    if err != nil { return }
    for {
        msg, err := stream.Recv()
        if errors.Is(err, context.Canceled) { break }
    }
}
   ```
2. **Use a separate context for stream to avoid parent cancellation.** (85% 成功率)
   ```
   streamCtx, cancel := context.WithCancel(context.Background())
defer cancel()
stream, _ := client.StreamRPC(streamCtx)
   ```

## 无效尝试

- **Ignore the cancellation and retry the same stream.** — Stream is closed; must create a new stream. (95% 失败率)
- **Increase context timeout to avoid cancellation.** — Cancellation may be intentional (e.g., user abort). (70% 失败率)
