# rpc错误：代码=已取消 描述=上下文已取消

- **ID:** `go/grpc-canceled-context-cancelled`
- **领域:** go
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

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

## 解决方案

1. **Create a new context for each RPC call to avoid using cancelled contexts.** (90% 成功率)
   ```
   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. **Handle cancellation gracefully by checking context errors.** (85% 成功率)
   ```
   select {
case <-ctx.Done():
    return nil, ctx.Err()
default:
}
resp, err := client.SomeRPC(ctx, req)
   ```

## 无效尝试

- **Ignore the cancellation and retry with the same context.** — The cancelled context cannot be reused; a new context is needed. (100% 失败率)
- **Remove context cancellation logic entirely.** — This can lead to resource leaks and unresponsive applications. (90% 失败率)
