0
# Exception Handling
1
2
Comprehensive exception classes for handling various types of Overpass API errors. These exceptions provide specific error information to help diagnose and handle different failure modes when querying the Overpass API.
3
4
## Capabilities
5
6
### Base Exception Class
7
8
Base exception class for all Overpass API-related errors.
9
10
```python { .api }
11
class OverpassError(Exception):
12
"""
13
Base exception class for all Overpass API errors.
14
15
Super class that all other Overpass exceptions inherit from.
16
Use this for general exception handling when you want to catch
17
any Overpass-related error.
18
"""
19
```
20
21
#### Usage Example
22
23
```python
24
import overpass
25
26
api = overpass.API()
27
28
try:
29
response = api.get('invalid query syntax')
30
except overpass.OverpassError as e:
31
print(f"Overpass error occurred: {e}")
32
# Handle any Overpass-related error
33
```
34
35
### Syntax Error Exception
36
37
Exception raised when the Overpass query contains syntax errors.
38
39
```python { .api }
40
class OverpassSyntaxError(OverpassError, ValueError):
41
"""
42
Exception for syntax errors in Overpass queries.
43
44
Inherits from both OverpassError and ValueError.
45
Raised when the Overpass API returns HTTP 400 indicating malformed query.
46
"""
47
48
def __init__(self, request: str):
49
"""
50
Args:
51
request: The malformed request that caused the error
52
"""
53
self.request = request
54
```
55
56
#### Usage Example
57
58
```python
59
try:
60
# Invalid Overpass QL syntax
61
response = api.get('node[name="City" invalid_syntax')
62
except overpass.OverpassSyntaxError as e:
63
print(f"Query syntax error: {e}")
64
print(f"Problematic query: {e.request}")
65
# Fix the query syntax and retry
66
```
67
68
### Timeout Exception
69
70
Exception raised when a request exceeds the configured timeout period.
71
72
```python { .api }
73
class TimeoutError(OverpassError):
74
"""
75
Exception for request timeouts.
76
77
Raised when the HTTP request to the Overpass API exceeds the timeout limit.
78
"""
79
80
def __init__(self, timeout: Union[int, float, Tuple[int, int]]):
81
"""
82
Args:
83
timeout: The timeout value that was exceeded
84
"""
85
self.timeout = timeout
86
```
87
88
#### Usage Example
89
90
```python
91
try:
92
# Long-running query that might timeout
93
response = api.get('way[highway=motorway](area:3602758138);')
94
except overpass.TimeoutError as e:
95
print(f"Query timed out after {e.timeout} seconds")
96
# Retry with longer timeout or simplify query
97
api = overpass.API(timeout=120) # Increase timeout
98
```
99
100
### Multiple Requests Exception
101
102
Exception raised when attempting to run multiple simultaneous requests.
103
104
```python { .api }
105
class MultipleRequestsError(OverpassError):
106
"""
107
Exception for multiple simultaneous requests.
108
109
Raised when the Overpass API returns HTTP 429 indicating that
110
the client is attempting multiple requests at the same time.
111
"""
112
```
113
114
#### Usage Example
115
116
```python
117
try:
118
# Don't do this - multiple simultaneous requests
119
import threading
120
121
def query_worker():
122
api.get('node["name"="City"]')
123
124
threads = [threading.Thread(target=query_worker) for _ in range(5)]
125
for t in threads:
126
t.start()
127
128
except overpass.MultipleRequestsError:
129
print("Cannot run multiple requests simultaneously")
130
# Implement request queuing or sequential execution
131
```
132
133
### Server Load Exception
134
135
Exception raised when the Overpass server is under high load and declines the request.
136
137
```python { .api }
138
class ServerLoadError(OverpassError):
139
"""
140
Exception when server is under load.
141
142
Raised when the Overpass API returns HTTP 504 indicating the server
143
is currently under load and declined the request.
144
"""
145
146
def __init__(self, timeout: Union[int, float, Tuple[int, int]]):
147
"""
148
Args:
149
timeout: The timeout value used for the failed request
150
"""
151
self.timeout = timeout
152
```
153
154
#### Usage Example
155
156
```python
157
import time
158
159
try:
160
response = api.get('complex_query_here')
161
except overpass.ServerLoadError as e:
162
print(f"Server is under load, timeout was {e.timeout}")
163
164
# Check server status and wait
165
wait_time = api.slot_available_countdown
166
if wait_time > 0:
167
print(f"Waiting {wait_time} seconds for server availability")
168
time.sleep(wait_time)
169
170
# Retry the request
171
response = api.get('complex_query_here')
172
```
173
174
### Server Runtime Error Exception
175
176
Exception raised when the Overpass server returns a runtime error.
177
178
```python { .api }
179
class ServerRuntimeError(OverpassError):
180
"""
181
Exception for server runtime errors.
182
183
Raised when the Overpass server encounters a runtime error during query execution.
184
This typically indicates issues with the query logic or server-side processing problems.
185
"""
186
187
def __init__(self, message: str):
188
"""
189
Args:
190
message: The runtime error message from the server
191
"""
192
self.message = message
193
```
194
195
#### Usage Example
196
197
```python
198
try:
199
# Query that might cause server runtime error
200
response = api.get('very_complex_query_with_potential_issues')
201
except overpass.ServerRuntimeError as e:
202
print(f"Server runtime error: {e.message}")
203
# Simplify query or report issue
204
```
205
206
### Unknown Error Exception
207
208
Exception for unhandled or unknown Overpass API errors.
209
210
```python { .api }
211
class UnknownOverpassError(OverpassError):
212
"""
213
Exception for unknown errors.
214
215
Raised when an unexpected error occurs during the request that
216
doesn't fit into other specific error categories.
217
"""
218
219
def __init__(self, message: str):
220
"""
221
Args:
222
message: Description of the unknown error
223
"""
224
self.message = message
225
```
226
227
#### Usage Example
228
229
```python
230
try:
231
response = api.get('node["name"="City"]')
232
except overpass.UnknownOverpassError as e:
233
print(f"Unknown error occurred: {e.message}")
234
# Log error details and possibly report to developers
235
```
236
237
## Exception Handling Patterns
238
239
### Comprehensive Error Handling
240
241
```python
242
import overpass
243
import time
244
245
def robust_query(api, query, max_retries=3):
246
"""Execute query with comprehensive error handling and retries."""
247
248
for attempt in range(max_retries):
249
try:
250
return api.get(query)
251
252
except overpass.OverpassSyntaxError as e:
253
print(f"Syntax error in query: {e.request}")
254
raise # Don't retry syntax errors
255
256
except overpass.TimeoutError as e:
257
print(f"Timeout after {e.timeout}s, attempt {attempt + 1}")
258
if attempt < max_retries - 1:
259
time.sleep(2 ** attempt) # Exponential backoff
260
continue
261
raise
262
263
except overpass.ServerLoadError as e:
264
print(f"Server under load, attempt {attempt + 1}")
265
wait_time = api.slot_available_countdown
266
if wait_time > 0 and attempt < max_retries - 1:
267
time.sleep(wait_time)
268
continue
269
raise
270
271
except overpass.MultipleRequestsError:
272
print("Multiple requests detected, waiting...")
273
time.sleep(5)
274
if attempt < max_retries - 1:
275
continue
276
raise
277
278
except overpass.ServerRuntimeError as e:
279
print(f"Server runtime error: {e.message}")
280
raise # Don't retry runtime errors - they're typically query logic issues
281
282
except overpass.OverpassError as e:
283
print(f"General Overpass error: {e}")
284
if attempt < max_retries - 1:
285
time.sleep(2 ** attempt)
286
continue
287
raise
288
289
raise Exception("Max retries exceeded")
290
291
# Usage
292
api = overpass.API()
293
try:
294
response = robust_query(api, 'node["name"="Salt Lake City"]')
295
except overpass.OverpassError:
296
print("Failed to execute query after all retries")
297
```
298
299
### Status Code Mapping
300
301
The exceptions are mapped to specific HTTP status codes:
302
303
- **400**: `OverpassSyntaxError` - Malformed query
304
- **429**: `MultipleRequestsError` - Too many simultaneous requests
305
- **504**: `ServerLoadError` - Server under load/timeout
306
- **Other codes**: `UnknownOverpassError` - Unexpected status codes