0
# Exception Handling
1
2
Comprehensive exception classes for handling both client-side and server-side errors with detailed error information and debugging capabilities. The SDK provides structured error handling to help developers identify and resolve issues quickly.
3
4
## Capabilities
5
6
### Client Exception
7
8
Client-side exceptions for SDK-related errors including invalid parameters, network issues, and authentication problems.
9
10
```python { .api }
11
class ClientException(Exception):
12
def __init__(self, code, msg):
13
"""
14
Initialize client exception for SDK-side errors.
15
16
Parameters:
17
- code (str): Error code identifying the specific error type
18
- msg (str): Human-readable error message
19
"""
20
21
def get_error_code(self):
22
"""
23
Get the error code for this exception.
24
25
Returns:
26
str: Error code identifying the error type
27
"""
28
29
def get_error_msg(self):
30
"""
31
Get the error message for this exception.
32
33
Returns:
34
str: Human-readable error message
35
"""
36
37
def get_error_type(self):
38
"""
39
Get the error type (always "Client" for ClientException).
40
41
Returns:
42
str: Error type identifier
43
"""
44
```
45
46
### Server Exception
47
48
Server-side exceptions for API errors returned by Alibaba Cloud services, including service errors and request validation failures.
49
50
```python { .api }
51
class ServerException(Exception):
52
def __init__(self, code, msg, http_status=None, request_id=None):
53
"""
54
Initialize server exception for API-side errors.
55
56
Parameters:
57
- code (str): Error code from the API response
58
- msg (str): Error message from the API response
59
- http_status (int, optional): HTTP status code of the response
60
- request_id (str, optional): Request ID for debugging and support
61
"""
62
63
def get_error_code(self):
64
"""
65
Get the API error code.
66
67
Returns:
68
str: API error code from the service response
69
"""
70
71
def get_error_msg(self):
72
"""
73
Get the API error message.
74
75
Returns:
76
str: Error message from the service response
77
"""
78
79
def get_error_type(self):
80
"""
81
Get the error type (always "Server" for ServerException).
82
83
Returns:
84
str: Error type identifier
85
"""
86
87
def get_http_status(self):
88
"""
89
Get the HTTP status code of the failed request.
90
91
Returns:
92
int: HTTP status code (e.g., 400, 403, 500)
93
"""
94
95
def get_request_id(self):
96
"""
97
Get the request ID for debugging purposes.
98
99
Returns:
100
str: Unique request identifier for support and debugging
101
"""
102
```
103
104
### Error Types
105
106
Constants defining different categories of errors for classification purposes.
107
108
```python { .api }
109
from aliyunsdkcore.acs_exception import error_type
110
111
ERROR_TYPE_CLIENT: str # "Client"
112
ERROR_TYPE_SERVER: str # "Server"
113
```
114
115
### Error Codes
116
117
Common error codes that may be encountered when using the SDK.
118
119
```python { .api }
120
from aliyunsdkcore.acs_exception import error_code
121
122
# Client error codes
123
SDK_INVALID_PARAMS: str
124
SDK_INVALID_REQUEST: str
125
SDK_INVALID_CREDENTIAL: str
126
SDK_NETWORK_ERROR: str
127
SDK_TIMEOUT_ERROR: str
128
SDK_HTTP_ERROR: str
129
130
# Server error codes (examples - actual codes vary by service)
131
INVALID_ACCESS_KEY_ID: str
132
SIGNATURE_DOES_NOT_MATCH: str
133
INVALID_PARAMETER: str
134
MISSING_PARAMETER: str
135
THROTTLING: str
136
INTERNAL_ERROR: str
137
```
138
139
### Error Messages
140
141
Predefined error messages for common error scenarios.
142
143
```python { .api }
144
from aliyunsdkcore.acs_exception import error_msg
145
146
# Get error message by code
147
def get_msg(error_code):
148
"""
149
Get predefined error message for a given error code.
150
151
Parameters:
152
- error_code (str): Error code
153
154
Returns:
155
str: Corresponding error message or generic message if not found
156
"""
157
```
158
159
## Usage Examples
160
161
### Basic Exception Handling
162
163
```python
164
from aliyunsdkcore.client import AcsClient
165
from aliyunsdkcore.request import CommonRequest
166
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
167
168
try:
169
# Create and execute request
170
client = AcsClient(ak="your-ak", secret="your-secret")
171
request = CommonRequest()
172
request.set_domain("ecs.cn-hangzhou.aliyuncs.com")
173
request.set_version("2014-05-26")
174
request.set_action_name("DescribeInstances")
175
request.set_method("POST")
176
177
response = client.do_action_with_exception(request)
178
print("Request successful:", response.decode('utf-8'))
179
180
except ClientException as e:
181
print(f"Client Error: {e.get_error_code()} - {e.get_error_msg()}")
182
print(f"Error Type: {e.get_error_type()}")
183
184
except ServerException as e:
185
print(f"Server Error: {e.get_error_code()} - {e.get_error_msg()}")
186
print(f"HTTP Status: {e.get_http_status()}")
187
print(f"Request ID: {e.get_request_id()}")
188
print(f"Error Type: {e.get_error_type()}")
189
```
190
191
### Specific Error Code Handling
192
193
```python
194
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
195
196
try:
197
response = client.do_action_with_exception(request)
198
199
except ClientException as e:
200
error_code = e.get_error_code()
201
202
if error_code == "SDK.InvalidCredential":
203
print("Invalid credentials - check your access key and secret")
204
elif error_code == "SDK.NetworkError":
205
print("Network connectivity issue - check your internet connection")
206
elif error_code == "SDK.TimeoutError":
207
print("Request timed out - try increasing timeout or retry")
208
else:
209
print(f"Unexpected client error: {error_code} - {e.get_error_msg()}")
210
211
except ServerException as e:
212
error_code = e.get_error_code()
213
214
if error_code == "InvalidAccessKeyId.NotFound":
215
print("Access Key ID not found - verify your credentials")
216
elif error_code == "SignatureDoesNotMatch":
217
print("Signature mismatch - check your access key secret")
218
elif error_code == "Throttling":
219
print("Request throttled - implement exponential backoff")
220
print(f"Request ID for support: {e.get_request_id()}")
221
elif error_code == "InternalError":
222
print("Service internal error - contact support")
223
print(f"Request ID: {e.get_request_id()}")
224
else:
225
print(f"API error: {error_code} - {e.get_error_msg()}")
226
print(f"Request ID: {e.get_request_id()}")
227
```
228
229
### Retry Logic with Exception Handling
230
231
```python
232
import time
233
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
234
235
def make_request_with_retry(client, request, max_retries=3):
236
"""Execute request with retry logic for transient errors."""
237
238
for attempt in range(max_retries + 1):
239
try:
240
response = client.do_action_with_exception(request)
241
return response.decode('utf-8')
242
243
except ClientException as e:
244
if attempt == max_retries:
245
raise # Re-raise on final attempt
246
247
error_code = e.get_error_code()
248
if error_code in ["SDK.NetworkError", "SDK.TimeoutError"]:
249
print(f"Retrying after client error: {error_code}")
250
time.sleep(2 ** attempt) # Exponential backoff
251
else:
252
raise # Don't retry non-transient client errors
253
254
except ServerException as e:
255
if attempt == max_retries:
256
raise # Re-raise on final attempt
257
258
error_code = e.get_error_code()
259
http_status = e.get_http_status()
260
261
# Retry on throttling and 5xx server errors
262
if error_code == "Throttling" or (http_status and http_status >= 500):
263
print(f"Retrying after server error: {error_code}")
264
time.sleep(2 ** attempt) # Exponential backoff
265
else:
266
raise # Don't retry 4xx client errors
267
268
# Usage
269
try:
270
result = make_request_with_retry(client, request)
271
print("Success:", result)
272
except (ClientException, ServerException) as e:
273
print(f"Failed after retries: {e.get_error_code()} - {e.get_error_msg()}")
274
```
275
276
### Error Logging and Debugging
277
278
```python
279
import logging
280
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
281
282
# Set up logging
283
logging.basicConfig(level=logging.INFO)
284
logger = logging.getLogger(__name__)
285
286
def execute_with_logging(client, request):
287
"""Execute request with comprehensive error logging."""
288
289
try:
290
logger.info("Executing API request...")
291
response = client.do_action_with_exception(request)
292
logger.info("Request completed successfully")
293
return response.decode('utf-8')
294
295
except ClientException as e:
296
logger.error(
297
"Client exception occurred: code=%s, message=%s, type=%s",
298
e.get_error_code(),
299
e.get_error_msg(),
300
e.get_error_type()
301
)
302
raise
303
304
except ServerException as e:
305
logger.error(
306
"Server exception occurred: code=%s, message=%s, status=%s, request_id=%s",
307
e.get_error_code(),
308
e.get_error_msg(),
309
e.get_http_status(),
310
e.get_request_id()
311
)
312
raise
313
```
314
315
### Custom Exception Handling
316
317
```python
318
class CustomAPIError(Exception):
319
"""Custom exception for application-specific error handling."""
320
321
def __init__(self, message, error_code=None, request_id=None):
322
super().__init__(message)
323
self.error_code = error_code
324
self.request_id = request_id
325
326
def safe_api_call(client, request):
327
"""Wrapper that converts SDK exceptions to custom exceptions."""
328
329
try:
330
response = client.do_action_with_exception(request)
331
return response.decode('utf-8')
332
333
except ClientException as e:
334
raise CustomAPIError(
335
f"SDK client error: {e.get_error_msg()}",
336
error_code=e.get_error_code()
337
)
338
339
except ServerException as e:
340
raise CustomAPIError(
341
f"API server error: {e.get_error_msg()}",
342
error_code=e.get_error_code(),
343
request_id=e.get_request_id()
344
)
345
346
# Usage
347
try:
348
result = safe_api_call(client, request)
349
print("Success:", result)
350
except CustomAPIError as e:
351
print(f"Application error: {e}")
352
if e.request_id:
353
print(f"Request ID: {e.request_id}")
354
```
355
356
## Common Error Scenarios
357
358
### Authentication Errors
359
360
- `InvalidAccessKeyId.NotFound`: Access key ID doesn't exist
361
- `SignatureDoesNotMatch`: Incorrect access key secret or signature computation
362
- `InvalidSecurityToken.Expired`: STS token has expired
363
- `InvalidSecurityToken.Malformed`: Malformed STS token
364
365
### Request Errors
366
367
- `MissingParameter`: Required parameter not provided
368
- `InvalidParameter`: Parameter value is invalid
369
- `Throttling`: Too many requests, rate limiting applied
370
- `RequestTimeTooSkewed`: Client clock is not synchronized
371
372
### Network Errors
373
374
- `SDK.NetworkError`: Network connectivity issues
375
- `SDK.TimeoutError`: Request timeout exceeded
376
- `SDK.HttpError`: HTTP-level errors (DNS resolution, connection failures)