0
# Exception Handling
1
2
Structured exception hierarchy for handling AWS service errors, connection issues, credential problems, and validation failures. Botocore provides specific exception types for different error categories to enable precise error handling.
3
4
## Capabilities
5
6
### Base Exceptions
7
8
Foundation exception classes for all botocore errors.
9
10
```python { .api }
11
class BotoCoreError(Exception):
12
"""Base exception for all botocore errors."""
13
pass
14
15
class ClientError(BotoCoreError):
16
"""
17
Service-specific errors returned by AWS APIs.
18
19
Attributes:
20
response: Complete error response from AWS service
21
operation_name: AWS operation that caused the error
22
"""
23
24
def __init__(self, error_response: dict, operation_name: str):
25
"""
26
Initialize client error.
27
28
Args:
29
error_response: Error response from AWS service
30
operation_name: AWS operation name
31
"""
32
self.response = error_response
33
self.operation_name = operation_name
34
```
35
36
### Connection Exceptions
37
38
Network and HTTP connection-related errors.
39
40
```python { .api }
41
class ConnectionError(BotoCoreError):
42
"""Base class for connection errors."""
43
pass
44
45
class EndpointConnectionError(ConnectionError):
46
"""
47
Error connecting to AWS service endpoint.
48
49
Attributes:
50
endpoint_url: URL that failed to connect
51
"""
52
pass
53
54
class SSLError(ConnectionError):
55
"""SSL/TLS certificate verification errors."""
56
pass
57
58
class ConnectTimeoutError(ConnectionError):
59
"""Connection timeout exceeded."""
60
pass
61
62
class ProxyConnectionError(ConnectionError):
63
"""Proxy connection failures."""
64
pass
65
66
class HTTPClientError(ConnectionError):
67
"""HTTP client-level errors."""
68
pass
69
```
70
71
### Credential Exceptions
72
73
AWS credential and authentication-related errors.
74
75
```python { .api }
76
class NoCredentialsError(BotoCoreError):
77
"""No AWS credentials found in credential chain."""
78
pass
79
80
class PartialCredentialsError(BotoCoreError):
81
"""
82
Incomplete AWS credentials found.
83
84
Raised when some but not all required credential components are available.
85
"""
86
pass
87
88
class CredentialRetrievalError(BotoCoreError):
89
"""Error retrieving credentials from provider."""
90
pass
91
92
class NoAuthTokenError(BotoCoreError):
93
"""Missing authentication token for token-based services."""
94
pass
95
96
class TokenRetrievalError(BotoCoreError):
97
"""Error retrieving authentication token."""
98
pass
99
```
100
101
### Configuration Exceptions
102
103
Configuration file and profile-related errors.
104
105
```python { .api }
106
class ProfileNotFound(BotoCoreError):
107
"""
108
AWS profile not found in configuration.
109
110
Attributes:
111
profile: Profile name that was not found
112
"""
113
pass
114
115
class ConfigNotFound(BotoCoreError):
116
"""AWS configuration file not found."""
117
pass
118
119
class ConfigParseError(BotoCoreError):
120
"""Error parsing AWS configuration file."""
121
pass
122
123
class InvalidConfigError(BotoCoreError):
124
"""Invalid configuration values."""
125
pass
126
```
127
128
### Service and Data Exceptions
129
130
AWS service discovery and data-related errors.
131
132
```python { .api }
133
class UnknownServiceError(BotoCoreError):
134
"""
135
Unknown AWS service name.
136
137
Attributes:
138
service_name: Service name that was not recognized
139
known_services: List of available service names
140
"""
141
pass
142
143
class DataNotFoundError(BotoCoreError):
144
"""Service data not found in botocore data directory."""
145
pass
146
147
class ApiVersionNotFoundError(BotoCoreError):
148
"""
149
Specified API version not found for service.
150
151
Attributes:
152
api_version: API version that was not found
153
available_api_versions: List of available API versions
154
"""
155
pass
156
157
class UnknownRegionError(BotoCoreError):
158
"""
159
Unknown AWS region name.
160
161
Attributes:
162
region_name: Region name that was not recognized
163
"""
164
pass
165
```
166
167
### Validation Exceptions
168
169
Parameter and input validation errors.
170
171
```python { .api }
172
class ParamValidationError(BotoCoreError):
173
"""
174
Parameter validation failure.
175
176
Attributes:
177
report: Validation error report with details
178
"""
179
pass
180
181
class ValidationError(BotoCoreError):
182
"""General validation error."""
183
pass
184
185
class MissingParametersError(ValidationError):
186
"""Required parameters missing from operation call."""
187
pass
188
189
class ParamValidationDecoratorError(ParamValidationError):
190
"""Parameter validation decorator error."""
191
pass
192
```
193
194
### Operation-Specific Exceptions
195
196
Errors specific to certain botocore operations.
197
198
```python { .api }
199
class PaginationError(BotoCoreError):
200
"""Pagination-related errors."""
201
pass
202
203
class WaiterError(BotoCoreError):
204
"""
205
Base class for waiter errors.
206
207
Attributes:
208
name: Waiter name
209
reason: Error reason
210
"""
211
pass
212
213
class WaiterConfigError(WaiterError):
214
"""Waiter configuration error."""
215
pass
216
217
class ChecksumError(BotoCoreError):
218
"""Checksum validation failure."""
219
pass
220
221
class EventStreamError(BotoCoreError):
222
"""Event streaming errors."""
223
pass
224
225
class InvalidRetryConfigurationError(BotoCoreError):
226
"""Invalid retry configuration."""
227
pass
228
229
class InvalidMaxRetryAttemptsError(InvalidRetryConfigurationError):
230
"""Invalid maximum retry attempts value."""
231
pass
232
233
class StubResponseError(BotoCoreError):
234
"""Testing stub response errors."""
235
pass
236
237
class UnStubbedResponseError(StubResponseError):
238
"""Response not stubbed in testing."""
239
pass
240
```
241
242
### Parsing and Serialization Exceptions
243
244
Data parsing and request serialization errors.
245
246
```python { .api }
247
class ResponseParserError(BotoCoreError):
248
"""Error parsing AWS service response."""
249
pass
250
251
class UnsupportedSignatureVersionError(BotoCoreError):
252
"""Unsupported AWS signature version."""
253
pass
254
255
class MissingDependencyException(BotoCoreError):
256
"""Required dependency not available."""
257
pass
258
```
259
260
## Usage Examples
261
262
### Handling Service Errors
263
264
```python
265
from botocore.exceptions import ClientError
266
267
try:
268
response = s3_client.get_object(Bucket='mybucket', Key='mykey')
269
except ClientError as e:
270
error_code = e.response['Error']['Code']
271
error_message = e.response['Error']['Message']
272
273
if error_code == 'NoSuchBucket':
274
print(f"Bucket does not exist: {error_message}")
275
elif error_code == 'NoSuchKey':
276
print(f"Object not found: {error_message}")
277
elif error_code == 'AccessDenied':
278
print(f"Access denied: {error_message}")
279
else:
280
print(f"Unexpected error {error_code}: {error_message}")
281
```
282
283
### Handling Connection Errors
284
285
```python
286
from botocore.exceptions import (
287
ConnectionError, EndpointConnectionError,
288
ConnectTimeoutError, SSLError
289
)
290
291
try:
292
client = session.create_client('s3', region_name='us-east-1')
293
response = client.list_buckets()
294
except EndpointConnectionError as e:
295
print(f"Cannot connect to AWS endpoint: {e}")
296
except ConnectTimeoutError:
297
print("Connection timeout - check network connectivity")
298
except SSLError as e:
299
print(f"SSL certificate error: {e}")
300
except ConnectionError as e:
301
print(f"Network connection error: {e}")
302
```
303
304
### Handling Credential Errors
305
306
```python
307
from botocore.exceptions import (
308
NoCredentialsError, PartialCredentialsError,
309
CredentialRetrievalError
310
)
311
312
try:
313
session = get_session()
314
credentials = session.get_credentials()
315
client = session.create_client('dynamodb')
316
except NoCredentialsError:
317
print("No AWS credentials found. Please configure credentials.")
318
except PartialCredentialsError:
319
print("Incomplete credentials found. Check configuration.")
320
except CredentialRetrievalError as e:
321
print(f"Failed to retrieve credentials: {e}")
322
```
323
324
### Handling Configuration Errors
325
326
```python
327
from botocore.exceptions import (
328
ProfileNotFound, ConfigNotFound,
329
UnknownServiceError, UnknownRegionError
330
)
331
332
try:
333
session = get_session()
334
session.profile = 'nonexistent-profile'
335
client = session.create_client('invalidservice', region_name='invalid-region')
336
except ProfileNotFound as e:
337
print(f"AWS profile not found: {e}")
338
except UnknownServiceError as e:
339
print(f"Unknown service: {e.service_name}")
340
print(f"Available services: {', '.join(e.known_services[:10])}...")
341
except UnknownRegionError as e:
342
print(f"Unknown region: {e.region_name}")
343
```
344
345
### Handling Validation Errors
346
347
```python
348
from botocore.exceptions import ParamValidationError, MissingParametersError
349
350
try:
351
# Missing required parameter
352
response = s3_client.get_object(Bucket='mybucket') # Missing Key parameter
353
except ParamValidationError as e:
354
print(f"Parameter validation failed: {e}")
355
# e.report contains detailed validation errors
356
except MissingParametersError as e:
357
print(f"Missing required parameters: {e}")
358
```
359
360
### Comprehensive Error Handling
361
362
```python
363
from botocore.exceptions import (
364
BotoCoreError, ClientError, NoCredentialsError,
365
ConnectionError, ValidationError
366
)
367
368
def robust_aws_operation():
369
try:
370
session = get_session()
371
client = session.create_client('s3', region_name='us-east-1')
372
373
response = client.list_buckets()
374
return response['Buckets']
375
376
except NoCredentialsError:
377
print("ERROR: No AWS credentials configured")
378
return None
379
except ConnectionError as e:
380
print(f"ERROR: Network connection failed: {e}")
381
return None
382
except ClientError as e:
383
error_code = e.response['Error']['Code']
384
if error_code == 'AccessDenied':
385
print("ERROR: Access denied - check IAM permissions")
386
else:
387
print(f"ERROR: AWS service error {error_code}: {e}")
388
return None
389
except ValidationError as e:
390
print(f"ERROR: Invalid parameters: {e}")
391
return None
392
except BotoCoreError as e:
393
print(f"ERROR: Botocore error: {e}")
394
return None
395
except Exception as e:
396
print(f"ERROR: Unexpected error: {e}")
397
return None
398
```
399
400
### Testing with Stub Errors
401
402
```python
403
from botocore.exceptions import ClientError
404
from botocore.stub import Stubber
405
406
def test_error_handling():
407
client = session.create_client('s3')
408
stubber = Stubber(client)
409
410
# Stub an error response
411
stubber.add_client_error(
412
'get_object',
413
service_error_code='NoSuchKey',
414
service_message='The specified key does not exist.',
415
expected_params={'Bucket': 'mybucket', 'Key': 'nonexistent'}
416
)
417
418
stubber.activate()
419
420
try:
421
client.get_object(Bucket='mybucket', Key='nonexistent')
422
except ClientError as e:
423
assert e.response['Error']['Code'] == 'NoSuchKey'
424
print("Error handling test passed")
425
426
stubber.deactivate()
427
```