0
# RPC Status and Error Handling
1
2
Standard RPC status codes, error details, and context information for robust error handling across Google services. Provides structured error reporting with detailed failure information and retry guidance.
3
4
## Capabilities
5
6
### Status Representation
7
8
Core status message for representing RPC operation results.
9
10
```python { .api }
11
from google.rpc.status_pb2 import Status
12
13
class Status(message.Message):
14
"""RPC status with error details."""
15
code: int # Status code (typically from Code enum)
16
message: str # Human-readable error message
17
details: list[Any] # Additional error details
18
```
19
20
### Standard Status Codes
21
22
Standardized gRPC status codes for consistent error handling.
23
24
```python { .api }
25
from google.rpc.code_pb2 import Code
26
27
class Code(enum.Enum):
28
"""Standard gRPC status codes."""
29
OK = 0 # Success
30
CANCELLED = 1 # Operation cancelled
31
UNKNOWN = 2 # Unknown error
32
INVALID_ARGUMENT = 3 # Invalid argument
33
DEADLINE_EXCEEDED = 4 # Deadline exceeded
34
NOT_FOUND = 5 # Resource not found
35
ALREADY_EXISTS = 6 # Resource already exists
36
PERMISSION_DENIED = 7 # Permission denied
37
RESOURCE_EXHAUSTED = 8 # Resource exhausted
38
FAILED_PRECONDITION = 9 # Failed precondition
39
ABORTED = 10 # Operation aborted
40
OUT_OF_RANGE = 11 # Out of range
41
UNIMPLEMENTED = 12 # Unimplemented
42
INTERNAL = 13 # Internal error
43
UNAVAILABLE = 14 # Service unavailable
44
DATA_LOSS = 15 # Data loss
45
UNAUTHENTICATED = 16 # Unauthenticated
46
```
47
48
### Detailed Error Information
49
50
Rich error details for specific failure scenarios.
51
52
```python { .api }
53
from google.rpc.error_details_pb2 import (
54
ErrorInfo, RetryInfo, DebugInfo, QuotaFailure,
55
PreconditionFailure, BadRequest, RequestInfo,
56
ResourceInfo, Help, LocalizedMessage
57
)
58
59
class ErrorInfo(message.Message):
60
"""Additional error information."""
61
reason: str # Error reason identifier
62
domain: str # Error domain
63
metadata: dict[str, str] # Additional metadata
64
65
class RetryInfo(message.Message):
66
"""Retry timing information."""
67
retry_delay: Duration # Recommended retry delay
68
69
class DebugInfo(message.Message):
70
"""Debug information for development."""
71
stack_entries: list[str] # Stack trace entries
72
detail: str # Additional debug details
73
74
class QuotaFailure(message.Message):
75
"""Quota failure details."""
76
violations: list[QuotaFailure.Violation] # Quota violations
77
78
class Violation(message.Message):
79
"""Individual quota violation."""
80
subject: str # Subject that violated quota
81
description: str # Violation description
82
83
class PreconditionFailure(message.Message):
84
"""Precondition failure details."""
85
violations: list[PreconditionFailure.Violation] # Precondition violations
86
87
class Violation(message.Message):
88
"""Individual precondition violation."""
89
type: str # Violation type
90
subject: str # Subject of violation
91
description: str # Violation description
92
93
class BadRequest(message.Message):
94
"""Bad request details."""
95
field_violations: list[BadRequest.FieldViolation] # Field violations
96
97
class FieldViolation(message.Message):
98
"""Individual field violation."""
99
field: str # Field path
100
description: str # Violation description
101
102
class RequestInfo(message.Message):
103
"""Request information for debugging."""
104
request_id: str # Unique request identifier
105
serving_data: str # Server-side data
106
107
class ResourceInfo(message.Message):
108
"""Resource information for errors."""
109
resource_type: str # Resource type identifier
110
resource_name: str # Resource name
111
owner: str # Resource owner
112
description: str # Resource description
113
114
class Help(message.Message):
115
"""Help information for error resolution."""
116
links: list[Help.Link] # Help links
117
118
class Link(message.Message):
119
"""Individual help link."""
120
description: str # Link description
121
url: str # Help URL
122
123
class LocalizedMessage(message.Message):
124
"""Localized error message."""
125
locale: str # Message locale
126
message: str # Localized message text
127
```
128
129
### Request Context Information
130
131
Contextual information about requests for debugging and auditing.
132
133
```python { .api }
134
from google.rpc.context.attribute_context_pb2 import AttributeContext
135
from google.rpc.context.audit_context_pb2 import AuditContext
136
137
class AttributeContext(message.Message):
138
"""Request attribute context."""
139
source: AttributeContext.Peer # Request source
140
destination: AttributeContext.Peer # Request destination
141
request: AttributeContext.Request # Request details
142
response: AttributeContext.Response # Response details
143
resource: AttributeContext.Resource # Target resource
144
api: AttributeContext.Api # API information
145
146
class Peer(message.Message):
147
"""Network peer information."""
148
ip: str # IP address
149
port: int # Port number
150
labels: dict[str, str] # Peer labels
151
principal: str # Authenticated principal
152
region_code: str # Geographic region
153
154
class Api(message.Message):
155
"""API information."""
156
service: str # Service name
157
operation: str # Operation name
158
protocol: str # Protocol used
159
version: str # API version
160
161
class Auth(message.Message):
162
"""Authentication information."""
163
principal: str # Authenticated principal
164
audiences: list[str] # Token audiences
165
presenter: str # Token presenter
166
claims: Struct # Additional claims
167
access_levels: list[str] # Access levels
168
169
class Request(message.Message):
170
"""Request information."""
171
id: str # Request ID
172
method: str # HTTP method
173
headers: dict[str, str] # Request headers
174
path: str # Request path
175
host: str # Request host
176
scheme: str # Request scheme
177
query: str # Query string
178
time: Timestamp # Request time
179
size: int # Request size
180
protocol: str # Protocol version
181
reason: str # Request reason
182
auth: AttributeContext.Auth # Authentication info
183
184
class AuditContext(message.Message):
185
"""Audit context information."""
186
audit_log_name: str # Audit log name
187
request_metadata: RequestMetadata # Request metadata
188
service_data: Any # Service-specific data
189
```
190
191
### HTTP-Specific Extensions
192
193
HTTP-specific RPC extensions and error mappings.
194
195
```python { .api }
196
from google.rpc.http_pb2 import HttpRequest, HttpResponse
197
198
class HttpRequest(message.Message):
199
"""HTTP request representation."""
200
method: str # HTTP method
201
uri: str # Request URI
202
headers: list[HttpHeader] # HTTP headers
203
body: bytes # Request body
204
205
class HttpResponse(message.Message):
206
"""HTTP response representation."""
207
status: int # HTTP status code
208
headers: list[HttpHeader] # Response headers
209
body: bytes # Response body
210
211
class HttpHeader(message.Message):
212
"""HTTP header representation."""
213
name: str # Header name
214
value: str # Header value
215
```
216
217
## Usage Examples
218
219
### Basic Status Creation
220
221
```python
222
from google.rpc.status_pb2 import Status
223
from google.rpc.code_pb2 import Code
224
225
# Create a status for invalid argument
226
status = Status()
227
status.code = Code.INVALID_ARGUMENT
228
status.message = "The 'name' field is required but was not provided"
229
```
230
231
### Detailed Error Information
232
233
```python
234
from google.rpc.error_details_pb2 import ErrorInfo, BadRequest
235
from google.protobuf.any_pb2 import Any
236
237
# Create detailed error information
238
error_info = ErrorInfo()
239
error_info.reason = "REQUIRED_FIELD_MISSING"
240
error_info.domain = "googleapis.com"
241
error_info.metadata["field"] = "name"
242
243
# Create field violation details
244
bad_request = BadRequest()
245
violation = bad_request.field_violations.add()
246
violation.field = "name"
247
violation.description = "This field is required"
248
249
# Pack into status details
250
status = Status()
251
status.code = Code.INVALID_ARGUMENT
252
status.message = "Request contains invalid arguments"
253
254
# Add error details
255
detail1 = Any()
256
detail1.Pack(error_info)
257
status.details.append(detail1)
258
259
detail2 = Any()
260
detail2.Pack(bad_request)
261
status.details.append(detail2)
262
```
263
264
### Retry Information
265
266
```python
267
from google.rpc.error_details_pb2 import RetryInfo
268
from google.protobuf.duration_pb2 import Duration
269
270
# Create retry information
271
retry_info = RetryInfo()
272
retry_info.retry_delay.seconds = 30 # Retry after 30 seconds
273
274
# Pack into status
275
status = Status()
276
status.code = Code.RESOURCE_EXHAUSTED
277
status.message = "Quota exceeded, retry after delay"
278
279
detail = Any()
280
detail.Pack(retry_info)
281
status.details.append(detail)
282
```
283
284
### Error Handling Pattern
285
286
```python
287
from google.rpc.status_pb2 import Status
288
from google.rpc.code_pb2 import Code
289
from google.rpc.error_details_pb2 import ErrorInfo, RetryInfo
290
291
def handle_rpc_error(status: Status):
292
"""Handle RPC error with detailed information."""
293
print(f"RPC failed with code {status.code}: {status.message}")
294
295
# Process error details
296
for detail in status.details:
297
if detail.Is(ErrorInfo.DESCRIPTOR):
298
error_info = ErrorInfo()
299
detail.Unpack(error_info)
300
print(f"Error reason: {error_info.reason}")
301
print(f"Error domain: {error_info.domain}")
302
303
elif detail.Is(RetryInfo.DESCRIPTOR):
304
retry_info = RetryInfo()
305
detail.Unpack(retry_info)
306
print(f"Retry after: {retry_info.retry_delay.seconds} seconds")
307
```
308
309
### Quote Failure Handling
310
311
```python
312
from google.rpc.error_details_pb2 import QuotaFailure
313
314
def handle_quota_failure(status: Status):
315
"""Handle quota failure with violation details."""
316
for detail in status.details:
317
if detail.Is(QuotaFailure.DESCRIPTOR):
318
quota_failure = QuotaFailure()
319
detail.Unpack(quota_failure)
320
321
for violation in quota_failure.violations:
322
print(f"Quota violation: {violation.subject}")
323
print(f"Description: {violation.description}")
324
```