# rpc错误：代码=前置条件失败 描述=资源未处于此操作的有效状态

- **ID:** `go/grpc-failed-precondition-state`
- **领域:** go
- **类别:** data_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

服务器拒绝请求，因为资源（例如数据库记录）处于不允许操作的状态，例如尝试删除已删除的项目。

## 版本兼容性

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

## 解决方案

1. **Check resource state before the RPC and handle accordingly.** (90% 成功率)
   ```
   state, _ := client.GetState(ctx, &pb.GetStateRequest{Id: id})
if state.Status != "active" { return errors.New("cannot perform operation on inactive resource") }
   ```
2. **Use a transactional pattern to ensure state validity.** (85% 成功率)
   ```
   // Implement optimistic locking with version field
req.Version = currentVersion
resp, err := client.UpdateResource(ctx, req)
if status.Code(err) == codes.FailedPrecondition { // retry with fresh version }
   ```

## 无效尝试

- **Retrying the same request immediately.** — Resource state hasn't changed; same error. (90% 失败率)
- **Ignoring the error and proceeding with other operations.** — May cause data inconsistency; need to handle the state. (80% 失败率)
