0
# Exception Handling
1
2
Comprehensive exception hierarchy for handling various error conditions during speed testing operations. All speedtest-cli exceptions inherit from the base SpeedtestException class, providing structured error handling for different failure scenarios.
3
4
```python
5
import speedtest
6
```
7
8
## Capabilities
9
10
### Base Exception
11
12
All speedtest-cli specific exceptions inherit from this base class.
13
14
```python { .api }
15
class SpeedtestException(Exception):
16
"""Base exception class for all speedtest-cli errors."""
17
```
18
19
### HTTP and Network Errors
20
21
Exceptions related to HTTP requests and network connectivity issues.
22
23
```python { .api }
24
class SpeedtestHTTPError(SpeedtestException):
25
"""HTTP request errors during speed testing operations."""
26
27
class SpeedtestConfigError(SpeedtestException):
28
"""Configuration retrieval errors."""
29
30
class ConfigRetrievalError(SpeedtestHTTPError):
31
"""Failed to retrieve speedtest.net configuration."""
32
33
class SpeedtestServersError(SpeedtestException):
34
"""Server list retrieval errors."""
35
36
class ServersRetrievalError(SpeedtestHTTPError):
37
"""Failed to retrieve server list from speedtest.net."""
38
```
39
40
### Server Selection Errors
41
42
Exceptions related to server discovery and selection processes.
43
44
```python { .api }
45
class InvalidServerIDType(SpeedtestException):
46
"""Invalid server ID type provided."""
47
48
class NoMatchedServers(SpeedtestException):
49
"""No servers match the provided criteria."""
50
51
class SpeedtestBestServerFailure(SpeedtestException):
52
"""Failed to determine best server through latency testing."""
53
54
class SpeedtestMissingBestServer(SpeedtestException):
55
"""Best server not set - call get_best_server() first."""
56
```
57
58
### Mini Server Errors
59
60
Exceptions specific to speedtest Mini server functionality.
61
62
```python { .api }
63
class SpeedtestMiniConnectFailure(SpeedtestException):
64
"""Failed to connect to specified Mini server."""
65
66
class InvalidSpeedtestMiniServer(SpeedtestException):
67
"""Invalid Mini server URL provided."""
68
```
69
70
### Test Execution Errors
71
72
Exceptions that occur during speed test execution.
73
74
```python { .api }
75
class SpeedtestUploadTimeout(SpeedtestException):
76
"""Upload test exceeded timeout duration."""
77
```
78
79
### Result Sharing Errors
80
81
Exceptions related to sharing test results on speedtest.net.
82
83
```python { .api }
84
class ShareResultsConnectFailure(SpeedtestException):
85
"""Failed to connect to speedtest.net share API."""
86
87
class ShareResultsSubmitFailure(SpeedtestException):
88
"""Failed to submit results to speedtest.net for sharing."""
89
```
90
91
### CLI Errors
92
93
Exceptions specific to command-line interface usage.
94
95
```python { .api }
96
class SpeedtestCLIError(SpeedtestException):
97
"""CLI-specific errors and invalid argument combinations."""
98
```
99
100
## Error Handling Patterns
101
102
### Basic Exception Handling
103
104
Handle common speedtest errors gracefully:
105
106
```python
107
import speedtest
108
109
try:
110
s = speedtest.Speedtest()
111
s.get_best_server()
112
s.download()
113
s.upload()
114
print(s.results.json(pretty=True))
115
116
except speedtest.ConfigRetrievalError:
117
print("Failed to retrieve speedtest configuration")
118
except speedtest.ServersRetrievalError:
119
print("Failed to retrieve server list")
120
except speedtest.NoMatchedServers:
121
print("No servers available for testing")
122
except speedtest.SpeedtestBestServerFailure:
123
print("Could not determine best server")
124
except speedtest.SpeedtestException as e:
125
print(f"Speed test failed: {e}")
126
```
127
128
### Server Selection Error Handling
129
130
Handle server-related errors with fallback options:
131
132
```python
133
import speedtest
134
135
s = speedtest.Speedtest()
136
137
try:
138
# Try to get servers
139
s.get_servers()
140
closest = s.get_closest_servers(limit=10)
141
142
# Try to find best server
143
best = s.get_best_server()
144
print(f"Selected server: {best['sponsor']}")
145
146
except speedtest.NoMatchedServers:
147
print("No servers match criteria, trying with no filters")
148
s.get_servers([]) # Get all servers
149
best = s.get_best_server()
150
151
except speedtest.SpeedtestBestServerFailure:
152
print("Auto-selection failed, using first available server")
153
s.best = s.closest[0] # Manually set first server
154
```
155
156
### Test Execution Error Handling
157
158
Handle errors during speed tests with retries:
159
160
```python
161
import speedtest
162
import time
163
164
s = speedtest.Speedtest()
165
s.get_best_server()
166
167
# Download test with retry
168
max_retries = 3
169
for attempt in range(max_retries):
170
try:
171
download_speed = s.download()
172
break
173
except speedtest.SpeedtestHTTPError as e:
174
if attempt < max_retries - 1:
175
print(f"Download failed (attempt {attempt + 1}): {e}")
176
time.sleep(2) # Wait before retry
177
else:
178
print("Download test failed after all retries")
179
raise
180
181
# Upload test with timeout handling
182
try:
183
upload_speed = s.upload()
184
except speedtest.SpeedtestUploadTimeout:
185
print("Upload test timed out - may indicate slow upload speed")
186
# Could retry with different parameters
187
upload_speed = s.upload(pre_allocate=False) # Use less memory
188
```
189
190
### Result Sharing Error Handling
191
192
Handle sharing failures gracefully:
193
194
```python
195
import speedtest
196
197
s = speedtest.Speedtest()
198
s.get_best_server()
199
s.download()
200
s.upload()
201
202
# Try to share results
203
try:
204
share_url = s.results.share()
205
print(f"Results shared: {share_url}")
206
except speedtest.ShareResultsConnectFailure:
207
print("Could not connect to sharing service")
208
except speedtest.ShareResultsSubmitFailure:
209
print("Failed to submit results for sharing")
210
except speedtest.SpeedtestHTTPError:
211
print("HTTP error occurred during sharing")
212
213
# Results are still available even if sharing fails
214
print("Local results:")
215
print(s.results.json(pretty=True))
216
```
217
218
### Mini Server Error Handling
219
220
Handle Mini server configuration errors:
221
222
```python
223
import speedtest
224
225
s = speedtest.Speedtest()
226
227
mini_url = "http://speedtest.example.com/mini"
228
try:
229
s.set_mini_server(mini_url)
230
s.download()
231
s.upload()
232
except speedtest.InvalidSpeedtestMiniServer:
233
print(f"Invalid Mini server URL: {mini_url}")
234
except speedtest.SpeedtestMiniConnectFailure:
235
print(f"Could not connect to Mini server: {mini_url}")
236
# Fall back to regular speedtest.net servers
237
s.get_best_server()
238
s.download()
239
s.upload()
240
```