0
# Exception Handling
1
2
Comprehensive exception hierarchy for handling AWS service errors, resource issues, and SDK-specific problems. Boto3 provides structured error handling that helps identify and respond to different failure scenarios in AWS operations.
3
4
## Capabilities
5
6
### Base Exception
7
8
The root exception class for all boto3-specific errors, providing a common base for exception handling patterns.
9
10
```python { .api }
11
class Boto3Error(Exception):
12
"""
13
Base class for all Boto3 errors.
14
15
All boto3-specific exceptions inherit from this class, allowing
16
for broad exception handling when needed.
17
"""
18
```
19
20
### Resource Management Exceptions
21
22
Exceptions related to AWS resource creation, loading, and API version management.
23
24
```python { .api }
25
class ResourceNotExistsError(Boto3Error):
26
"""
27
Raised when attempting to create a resource that does not exist.
28
29
This occurs when trying to create a resource for a service that
30
doesn't support the resource interface, only the client interface.
31
"""
32
33
def __init__(self, service_name: str, available_services: List[str],
34
has_low_level_client: bool):
35
"""
36
Parameters:
37
- service_name: The requested service name
38
- available_services: List of services that support resources
39
- has_low_level_client: Whether a client interface exists for this service
40
"""
41
42
class UnknownAPIVersionError(Boto3Error):
43
"""
44
Raised when an invalid API version is specified for a service.
45
46
This occurs when requesting a specific API version that is not
47
available for the requested service.
48
"""
49
50
def __init__(self, service_name: str, bad_api_version: str,
51
available_api_versions: List[str]):
52
"""
53
Parameters:
54
- service_name: The service name
55
- bad_api_version: The invalid API version requested
56
- available_api_versions: List of valid API versions
57
"""
58
59
class ResourceLoadException(Boto3Error):
60
"""
61
General exception for errors that occur during resource loading.
62
63
This is raised when there are problems loading or initializing
64
AWS service resources.
65
"""
66
67
class NoVersionFound(Boto3Error):
68
"""
69
Raised when no API version can be found for a service.
70
71
Note: This exception is deprecated and may be removed in future versions.
72
"""
73
```
74
75
### Transfer Operation Exceptions
76
77
Exceptions specific to S3 transfer operations, including uploads, downloads, and retry scenarios.
78
79
```python { .api }
80
class RetriesExceededError(Boto3Error):
81
"""
82
Raised when the maximum number of retries has been exceeded.
83
84
This exception includes information about the last exception
85
that caused the retry to fail.
86
"""
87
88
def __init__(self, last_exception: Exception, msg: str = 'Max Retries Exceeded'):
89
"""
90
Parameters:
91
- last_exception: The final exception that caused failure
92
- msg: Error message describing the retry failure
93
"""
94
self.last_exception = last_exception
95
96
class S3TransferFailedError(Boto3Error):
97
"""
98
Raised when an S3 transfer operation fails.
99
100
This is a general exception for S3 transfer failures that
101
covers both upload and download operations.
102
"""
103
104
class S3UploadFailedError(Boto3Error):
105
"""
106
Raised when an S3 upload operation specifically fails.
107
108
This is used for upload-specific failures that may require
109
different handling than general transfer failures.
110
"""
111
```
112
113
### DynamoDB Operation Exceptions
114
115
Exceptions specific to DynamoDB operations, particularly around condition expressions and query parameters.
116
117
```python { .api }
118
class DynamoDBOperationNotSupportedError(Boto3Error):
119
"""
120
Raised when an unsupported operation is attempted on a DynamoDB value.
121
122
This occurs when trying to use condition operators directly on Python
123
values instead of using AttributeBase methods to create ConditionBase objects.
124
"""
125
126
def __init__(self, operation: str, value: Any):
127
"""
128
Parameters:
129
- operation: The operation that was attempted (e.g., 'AND', 'OR')
130
- value: The value that the operation was attempted on
131
"""
132
133
class DynamoDBNeedsConditionError(Boto3Error):
134
"""
135
Raised when a ConditionBase object is expected but not provided.
136
137
This occurs when DynamoDB operations require condition expressions
138
but receive incompatible value types instead.
139
"""
140
141
def __init__(self, value: Any):
142
"""
143
Parameters:
144
- value: The invalid value that was provided instead of a condition
145
"""
146
147
class DynamoDBNeedsKeyConditionError(Boto3Error):
148
"""
149
Raised when a key condition is required but not provided.
150
151
This occurs in DynamoDB query operations that require key conditions
152
to specify which items to retrieve.
153
"""
154
```
155
156
### Warning Classes
157
158
Warning classes for deprecated functionality and version compatibility issues.
159
160
```python { .api }
161
class PythonDeprecationWarning(Warning):
162
"""
163
Warning for Python versions scheduled to become unsupported.
164
165
This warning is emitted when using boto3 with Python versions
166
that will be deprecated in future releases.
167
"""
168
```
169
170
## Usage Examples
171
172
### Basic Exception Handling
173
174
```python
175
import boto3
176
from boto3.exceptions import Boto3Error, ResourceNotExistsError
177
178
try:
179
# Try to create a resource for a service that might not support it
180
service = boto3.resource('route53') # Route53 doesn't support resources
181
except ResourceNotExistsError as e:
182
print(f"Resource not available: {e}")
183
# Fall back to client interface
184
service = boto3.client('route53')
185
except Boto3Error as e:
186
print(f"General boto3 error: {e}")
187
```
188
189
### DynamoDB Exception Handling
190
191
```python
192
import boto3
193
from boto3.dynamodb.conditions import Key, Attr
194
from boto3.exceptions import DynamoDBOperationNotSupportedError
195
196
try:
197
# Correct usage with Key and Attr objects
198
condition = Key('pk').eq('value') & Attr('sk').begins_with('prefix')
199
200
# This would raise an exception:
201
# bad_condition = 'pk' == 'value' # Can't use string directly
202
203
except DynamoDBOperationNotSupportedError as e:
204
print(f"Invalid DynamoDB operation: {e}")
205
```
206
207
### S3 Transfer Exception Handling
208
209
```python
210
import boto3
211
from boto3.exceptions import S3UploadFailedError, RetriesExceededError
212
213
s3_client = boto3.client('s3')
214
215
try:
216
s3_client.upload_file('large-file.zip', 'my-bucket', 'uploads/large-file.zip')
217
except S3UploadFailedError as e:
218
print(f"S3 upload failed: {e}")
219
except RetriesExceededError as e:
220
print(f"Upload retries exceeded. Last error: {e.last_exception}")
221
```
222
223
### Service Discovery with Exception Handling
224
225
```python
226
import boto3
227
from boto3.exceptions import UnknownAPIVersionError
228
229
session = boto3.Session()
230
231
try:
232
# Try to use a specific API version
233
dynamodb = session.resource('dynamodb', api_version='2010-01-01') # Old version
234
except UnknownAPIVersionError as e:
235
print(f"API version not available: {e}")
236
# Use the default/latest version instead
237
dynamodb = session.resource('dynamodb')
238
```
239
240
### Comprehensive Error Handling Pattern
241
242
```python
243
import boto3
244
from boto3.exceptions import (
245
Boto3Error, ResourceNotExistsError, UnknownAPIVersionError,
246
S3TransferFailedError, DynamoDBOperationNotSupportedError
247
)
248
from botocore.exceptions import NoCredentialsError, ClientError
249
250
def create_aws_service(service_name, use_resource=True):
251
"""
252
Create AWS service with comprehensive error handling.
253
"""
254
try:
255
if use_resource:
256
return boto3.resource(service_name)
257
else:
258
return boto3.client(service_name)
259
260
except ResourceNotExistsError:
261
print(f"Resource interface not available for {service_name}, using client")
262
return boto3.client(service_name)
263
264
except UnknownAPIVersionError as e:
265
print(f"API version issue: {e}")
266
return boto3.client(service_name) # Use default version
267
268
except NoCredentialsError:
269
print("AWS credentials not found. Please configure credentials.")
270
raise
271
272
except ClientError as e:
273
print(f"AWS service error: {e}")
274
raise
275
276
except Boto3Error as e:
277
print(f"Boto3 error: {e}")
278
raise
279
```