0
# Exception Handling
1
2
Comprehensive exception hierarchy that maps HTTP and gRPC status codes to specific Python exceptions, providing consistent error handling across all Google API client libraries.
3
4
## Capabilities
5
6
### Base Exception Classes
7
8
Root exception classes that serve as the foundation for all Google API client errors.
9
10
```python { .api }
11
class GoogleAPIError(Exception):
12
"""Base class for all Google API client exceptions."""
13
14
class DuplicateCredentialArgs(GoogleAPIError):
15
"""Raised when multiple credentials are provided to a function or method."""
16
17
class RetryError(GoogleAPIError):
18
"""Raised when a function has exhausted all of its available retries."""
19
20
class GoogleAPICallError(GoogleAPIError):
21
"""Base class for exceptions raised by calling API methods."""
22
```
23
24
### HTTP Status Exception Hierarchy
25
26
Exception classes that map HTTP status codes to specific Python exceptions, maintaining the standard HTTP status code structure.
27
28
```python { .api }
29
# 3xx Redirection
30
class Redirection(GoogleAPICallError):
31
"""Base class for HTTP 3xx redirection responses."""
32
33
class MovedPermanently(Redirection):
34
"""HTTP 301 Moved Permanently."""
35
36
class NotModified(Redirection):
37
"""HTTP 304 Not Modified."""
38
39
class TemporaryRedirect(Redirection):
40
"""HTTP 307 Temporary Redirect."""
41
42
class ResumeIncomplete(Redirection):
43
"""HTTP 308 Resume Incomplete."""
44
45
# 4xx Client Error
46
class ClientError(GoogleAPICallError):
47
"""Base class for HTTP 4xx client error responses."""
48
49
class BadRequest(ClientError):
50
"""HTTP 400 Bad Request."""
51
52
class InvalidArgument(BadRequest):
53
"""gRPC INVALID_ARGUMENT error."""
54
55
class FailedPrecondition(BadRequest):
56
"""gRPC FAILED_PRECONDITION error."""
57
58
class OutOfRange(BadRequest):
59
"""gRPC OUT_OF_RANGE error."""
60
61
class Unauthorized(ClientError):
62
"""HTTP 401 Unauthorized."""
63
64
class Unauthenticated(Unauthorized):
65
"""gRPC UNAUTHENTICATED error."""
66
67
class Forbidden(ClientError):
68
"""HTTP 403 Forbidden."""
69
70
class PermissionDenied(Forbidden):
71
"""gRPC PERMISSION_DENIED error."""
72
73
class NotFound(ClientError):
74
"""HTTP 404 Not Found or gRPC NOT_FOUND error."""
75
76
class MethodNotAllowed(ClientError):
77
"""HTTP 405 Method Not Allowed."""
78
79
class Conflict(ClientError):
80
"""HTTP 409 Conflict."""
81
82
class AlreadyExists(Conflict):
83
"""gRPC ALREADY_EXISTS error."""
84
85
class Aborted(Conflict):
86
"""gRPC ABORTED error."""
87
88
class LengthRequired(ClientError):
89
"""HTTP 411 Length Required."""
90
91
class PreconditionFailed(ClientError):
92
"""HTTP 412 Precondition Failed."""
93
94
class RequestRangeNotSatisfiable(ClientError):
95
"""HTTP 416 Request Range Not Satisfiable."""
96
97
class TooManyRequests(ClientError):
98
"""HTTP 429 Too Many Requests."""
99
100
class ResourceExhausted(TooManyRequests):
101
"""gRPC RESOURCE_EXHAUSTED error."""
102
103
class Cancelled(ClientError):
104
"""HTTP 499 or gRPC CANCELLED error."""
105
106
# 5xx Server Error
107
class ServerError(GoogleAPICallError):
108
"""Base class for HTTP 5xx server error responses."""
109
110
class InternalServerError(ServerError):
111
"""HTTP 500 Internal Server Error or gRPC INTERNAL error."""
112
113
class Unknown(ServerError):
114
"""gRPC UNKNOWN error."""
115
116
class DataLoss(ServerError):
117
"""gRPC DATA_LOSS error."""
118
119
class MethodNotImplemented(ServerError):
120
"""HTTP 501 Not Implemented or gRPC UNIMPLEMENTED error."""
121
122
class BadGateway(ServerError):
123
"""HTTP 502 Bad Gateway."""
124
125
class ServiceUnavailable(ServerError):
126
"""HTTP 503 Service Unavailable or gRPC UNAVAILABLE error."""
127
128
class GatewayTimeout(ServerError):
129
"""HTTP 504 Gateway Timeout."""
130
131
class DeadlineExceeded(GatewayTimeout):
132
"""gRPC DEADLINE_EXCEEDED error."""
133
134
# Async REST specific
135
class AsyncRestUnsupportedParameterError(GoogleAPIError):
136
"""Exception for unsupported parameters in async REST transport."""
137
```
138
139
### Exception Utility Functions
140
141
Functions for creating and converting exceptions between different transport protocols.
142
143
```python { .api }
144
def exception_class_for_http_status(status_code):
145
"""
146
Return the appropriate exception class for the given HTTP status code.
147
148
Args:
149
status_code (int): HTTP status code
150
151
Returns:
152
type: Exception class corresponding to the status code
153
"""
154
155
def from_http_status(status_code, message, **kwargs):
156
"""
157
Create a GoogleAPICallError from an HTTP status code.
158
159
Args:
160
status_code (int): HTTP status code
161
message (str): Error message
162
**kwargs: Additional keyword arguments for the exception
163
164
Returns:
165
GoogleAPICallError: Exception instance for the status code
166
"""
167
168
def format_http_response_error(response, method, url, payload):
169
"""
170
Create an error message and response details from an HTTP response.
171
172
Args:
173
response: HTTP response object
174
method (str): HTTP method used
175
url (str): Request URL
176
payload: Request payload
177
178
Returns:
179
str: Formatted error message
180
"""
181
182
def from_http_response(response):
183
"""
184
Create a GoogleAPICallError from a requests.Response object.
185
186
Args:
187
response: requests.Response object
188
189
Returns:
190
GoogleAPICallError: Exception created from the response
191
"""
192
193
def exception_class_for_grpc_status(status_code):
194
"""
195
Return the appropriate exception class for the given gRPC status code.
196
197
Args:
198
status_code (int): gRPC status code
199
200
Returns:
201
type: Exception class corresponding to the gRPC status
202
"""
203
204
def from_grpc_status(status_code, message, **kwargs):
205
"""
206
Create a GoogleAPICallError from a gRPC status code.
207
208
Args:
209
status_code (int): gRPC status code
210
message (str): Error message
211
**kwargs: Additional keyword arguments for the exception
212
213
Returns:
214
GoogleAPICallError: Exception instance for the status code
215
"""
216
217
def from_grpc_error(rpc_exc):
218
"""
219
Create a GoogleAPICallError from a gRPC RpcError.
220
221
Args:
222
rpc_exc: gRPC RpcError exception
223
224
Returns:
225
GoogleAPICallError: Exception created from the gRPC error
226
"""
227
```
228
229
## Usage Examples
230
231
### Basic Exception Handling
232
233
```python
234
from google.api_core import exceptions
235
import requests
236
237
try:
238
response = requests.get("https://api.example.com/data")
239
response.raise_for_status()
240
except requests.HTTPError as http_error:
241
# Convert to Google API Core exception
242
api_error = exceptions.from_http_response(response)
243
244
if isinstance(api_error, exceptions.NotFound):
245
print("Resource not found")
246
elif isinstance(api_error, exceptions.ServerError):
247
print("Server error occurred")
248
else:
249
print(f"API error: {api_error}")
250
```
251
252
### Creating Custom Exception Predicates
253
254
```python
255
from google.api_core import exceptions
256
257
def is_retryable_error(exception):
258
"""Check if an exception should trigger a retry."""
259
return isinstance(exception, (
260
exceptions.InternalServerError,
261
exceptions.ServiceUnavailable,
262
exceptions.DeadlineExceeded,
263
exceptions.TooManyRequests
264
))
265
266
# Use with retry logic
267
from google.api_core import retry
268
retry_config = retry.Retry(predicate=is_retryable_error)
269
```
270
271
### Exception Status Code Mapping
272
273
```python
274
from google.api_core import exceptions
275
276
# Map HTTP status codes to exceptions
277
error_class = exceptions.exception_class_for_http_status(404)
278
print(error_class) # <class 'google.api_core.exceptions.NotFound'>
279
280
# Create exception from status
281
error = exceptions.from_http_status(500, "Internal server error")
282
print(type(error)) # <class 'google.api_core.exceptions.InternalServerError'>
283
```