0
# Error Handling
1
2
Comprehensive exception hierarchy following DB API 2.0 standards, with specialized exceptions for RPC communication, HiveServer2-specific errors, and transport issues.
3
4
## Capabilities
5
6
### Base Exception Classes
7
8
Foundation exception classes providing the base for all database-related errors.
9
10
```python { .api }
11
class Error(Exception):
12
"""Base exception class for all database errors."""
13
14
class Warning(Exception):
15
"""Exception for important warnings like data truncations."""
16
```
17
18
### DB API 2.0 Standard Exceptions
19
20
Standard database exception hierarchy as defined by DB API 2.0 (PEP 249).
21
22
```python { .api }
23
class InterfaceError(Error):
24
"""
25
Exception for interface-related errors.
26
27
Raised for errors related to the database interface rather than
28
the database itself.
29
"""
30
31
class DatabaseError(Error):
32
"""
33
Exception for database-related errors.
34
35
Base class for all errors related to the database operation.
36
"""
37
38
class InternalError(DatabaseError):
39
"""
40
Exception for internal database errors.
41
42
Raised when the database encounters an internal error.
43
"""
44
45
class OperationalError(DatabaseError):
46
"""
47
Exception for operational errors.
48
49
Raised for errors related to database operation and not necessarily
50
under user control (connection lost, memory allocation error, etc.).
51
"""
52
53
class ProgrammingError(DatabaseError):
54
"""
55
Exception for programming errors.
56
57
Raised for errors due to problems with the SQL statement or
58
parameters (table not found, syntax error, wrong number of
59
parameters, etc.).
60
"""
61
62
class IntegrityError(DatabaseError):
63
"""
64
Exception for data integrity errors.
65
66
Raised when data integrity of the database is affected
67
(foreign key check fails, duplicate key, etc.).
68
"""
69
70
class DataError(DatabaseError):
71
"""
72
Exception for data-related errors.
73
74
Raised for errors due to problems with the processed data
75
(division by zero, numeric value out of range, etc.).
76
"""
77
78
class NotSupportedError(DatabaseError):
79
"""
80
Exception for unsupported operations.
81
82
Raised when a method or database API was used which is not
83
supported by the database.
84
"""
85
```
86
87
### HiveServer2 and RPC Exceptions
88
89
Specialized exceptions for HiveServer2 protocol and RPC communication errors.
90
91
```python { .api }
92
class RPCError(Error):
93
"""
94
Exception for RPC communication errors.
95
96
Base class for errors that occur during Thrift RPC communication
97
with the HiveServer2 service.
98
"""
99
100
class HiveServer2Error(RPCError):
101
"""
102
Exception for HiveServer2-specific errors.
103
104
Raised for errors specific to HiveServer2 operations
105
and protocol handling.
106
"""
107
108
class HttpError(RPCError):
109
"""
110
Exception for HTTP transport errors.
111
112
Raised when errors occur during HTTP-based transport
113
communication with HiveServer2.
114
"""
115
116
class BeeswaxError(RPCError):
117
"""
118
Exception for Beeswax protocol errors.
119
120
Raised for errors related to the legacy Beeswax protocol
121
(mainly for older Hive versions).
122
"""
123
124
class QueryStateError(BeeswaxError):
125
"""
126
Exception for query state errors.
127
128
Raised when query execution encounters state-related issues
129
(query cancelled, timeout, invalid state transitions).
130
"""
131
132
class DisconnectedError(BeeswaxError):
133
"""
134
Exception for connection disconnection errors.
135
136
Raised when the connection to HiveServer2 is unexpectedly
137
lost or cannot be established.
138
"""
139
```
140
141
## Usage Examples
142
143
### Basic Error Handling
144
145
```python
146
from impala.dbapi import connect
147
from impala.error import Error, OperationalError, ProgrammingError
148
149
try:
150
conn = connect(host='impala-host', port=21050)
151
cursor = conn.cursor()
152
153
# This might raise ProgrammingError for SQL syntax issues
154
cursor.execute("SELECT * FROM non_existent_table")
155
results = cursor.fetchall()
156
157
except ProgrammingError as e:
158
print(f"SQL Programming Error: {e}")
159
except OperationalError as e:
160
print(f"Operational Error (connection, etc.): {e}")
161
except Error as e:
162
print(f"General Database Error: {e}")
163
finally:
164
if 'cursor' in locals():
165
cursor.close()
166
if 'conn' in locals():
167
conn.close()
168
```
169
170
### Connection Error Handling
171
172
```python
173
from impala.dbapi import connect
174
from impala.error import OperationalError, DisconnectedError, RPCError
175
176
def robust_connect(host, port, max_retries=3):
177
"""Connect with retry logic and proper error handling."""
178
179
for attempt in range(max_retries):
180
try:
181
conn = connect(host=host, port=port, timeout=10)
182
return conn
183
184
except DisconnectedError as e:
185
print(f"Connection attempt {attempt + 1} failed: {e}")
186
if attempt == max_retries - 1:
187
raise
188
189
except RPCError as e:
190
print(f"RPC Error on attempt {attempt + 1}: {e}")
191
if attempt == max_retries - 1:
192
raise
193
194
except OperationalError as e:
195
print(f"Operational error on attempt {attempt + 1}: {e}")
196
if attempt == max_retries - 1:
197
raise
198
199
# Usage
200
try:
201
connection = robust_connect('impala-cluster.example.com', 21050)
202
print("Successfully connected to Impala")
203
except Exception as e:
204
print(f"Failed to connect after retries: {e}")
205
```
206
207
### Query Execution Error Handling
208
209
```python
210
from impala.dbapi import connect
211
from impala.error import (
212
ProgrammingError, DataError, QueryStateError,
213
NotSupportedError, InternalError
214
)
215
216
def execute_with_error_handling(cursor, query, params=None):
217
"""Execute query with comprehensive error handling."""
218
219
try:
220
cursor.execute(query, params)
221
return cursor.fetchall()
222
223
except ProgrammingError as e:
224
# SQL syntax errors, table not found, etc.
225
print(f"SQL Programming Error: {e}")
226
print("Check your SQL syntax and table/column names")
227
raise
228
229
except DataError as e:
230
# Data type issues, value out of range, etc.
231
print(f"Data Error: {e}")
232
print("Check your data types and value ranges")
233
raise
234
235
except QueryStateError as e:
236
# Query was cancelled or timed out
237
print(f"Query State Error: {e}")
238
print("Query may have been cancelled or timed out")
239
raise
240
241
except NotSupportedError as e:
242
# Unsupported SQL features
243
print(f"Feature Not Supported: {e}")
244
print("This SQL feature is not supported by Impala/Hive")
245
raise
246
247
except InternalError as e:
248
# Internal database errors
249
print(f"Internal Database Error: {e}")
250
print("This appears to be an internal database issue")
251
raise
252
253
# Usage
254
conn = connect(host='impala-host', port=21050)
255
cursor = conn.cursor()
256
257
try:
258
results = execute_with_error_handling(
259
cursor,
260
"SELECT * FROM sales WHERE date > %(start_date)s",
261
{'start_date': '2023-01-01'}
262
)
263
for row in results:
264
print(row)
265
266
finally:
267
cursor.close()
268
conn.close()
269
```
270
271
### Authentication Error Handling
272
273
```python
274
from impala.dbapi import connect
275
from impala.error import InterfaceError, OperationalError
276
277
def connect_with_auth_fallback(host, port, auth_configs):
278
"""Try multiple authentication mechanisms."""
279
280
for auth_config in auth_configs:
281
try:
282
print(f"Trying authentication: {auth_config['auth_mechanism']}")
283
conn = connect(host=host, port=port, **auth_config)
284
285
# Test the connection
286
cursor = conn.cursor()
287
cursor.execute("SELECT 1")
288
cursor.fetchone()
289
cursor.close()
290
291
print(f"Successfully authenticated with: {auth_config['auth_mechanism']}")
292
return conn
293
294
except InterfaceError as e:
295
print(f"Interface error with {auth_config['auth_mechanism']}: {e}")
296
continue
297
298
except OperationalError as e:
299
print(f"Auth failed with {auth_config['auth_mechanism']}: {e}")
300
continue
301
302
raise Exception("All authentication methods failed")
303
304
# Usage
305
auth_methods = [
306
{'auth_mechanism': 'GSSAPI'}, # Try Kerberos first
307
{'auth_mechanism': 'LDAP', 'user': 'username', 'password': 'password'},
308
{'auth_mechanism': 'NOSASL'}, # Fallback to no auth
309
]
310
311
try:
312
connection = connect_with_auth_fallback(
313
'impala-host', 21050, auth_methods
314
)
315
except Exception as e:
316
print(f"Authentication failed: {e}")
317
```
318
319
### HTTP Transport Error Handling
320
321
```python
322
from impala.dbapi import connect
323
from impala.error import HttpError, OperationalError
324
325
try:
326
# Connect using HTTP transport
327
conn = connect(
328
host='impala-gateway.example.com',
329
port=28000, # HTTP port
330
use_http_transport=True,
331
http_path='cliservice',
332
use_ssl=True
333
)
334
335
cursor = conn.cursor()
336
cursor.execute("SELECT version()")
337
result = cursor.fetchone()
338
print(f"Connected via HTTP: {result[0]}")
339
340
except HttpError as e:
341
print(f"HTTP Transport Error: {e}")
342
print("Check HTTP transport configuration and proxy settings")
343
344
except OperationalError as e:
345
print(f"Connection Error: {e}")
346
print("Check host, port, and network connectivity")
347
348
finally:
349
if 'cursor' in locals():
350
cursor.close()
351
if 'conn' in locals():
352
conn.close()
353
```