0
# Error Handling
1
2
Complete DB API 2.0 exception hierarchy with Phoenix-specific error information including SQL state codes, error codes, and detailed error messages for comprehensive error handling.
3
4
## Capabilities
5
6
### Exception Hierarchy
7
8
phoenixdb implements the full DB API 2.0 exception hierarchy for standardized error handling.
9
10
```python { .api }
11
class Warning(Exception):
12
"""
13
Not used by phoenixdb, only defined for DB API 2.0 compatibility.
14
"""
15
16
class Error(Exception):
17
"""
18
Base class for all other error exceptions.
19
Can be used to catch all errors with single except statement.
20
"""
21
22
def __init__(self, message, code=None, sqlstate=None, cause=None): ...
23
24
@property
25
def message(self):
26
"""Error message string."""
27
28
@property
29
def code(self):
30
"""Phoenix/database error code (integer or None)."""
31
32
@property
33
def sqlstate(self):
34
"""SQL state code string (SQLSTATE standard)."""
35
36
@property
37
def cause(self):
38
"""Underlying cause exception or None."""
39
40
class InterfaceError(Error):
41
"""
42
Errors related to the database interface rather than the database itself.
43
Examples: connection problems, parameter issues, API usage errors.
44
"""
45
46
class DatabaseError(Error):
47
"""
48
Base class for errors related to the database.
49
All database-specific errors inherit from this.
50
"""
51
52
class DataError(DatabaseError):
53
"""
54
Errors due to problems with processed data.
55
Examples: division by zero, numeric value out of range, type conversion errors.
56
"""
57
58
class OperationalError(DatabaseError):
59
"""
60
Errors related to database operation, not necessarily under programmer control.
61
Examples: disconnect, memory allocation error, transaction processing failure.
62
"""
63
64
class IntegrityError(DatabaseError):
65
"""
66
Errors when relational integrity of database is affected.
67
Examples: foreign key check fails, unique constraint violation.
68
"""
69
70
class InternalError(DatabaseError):
71
"""
72
Errors when database encounters an internal problem.
73
Examples: cursor not valid, transaction out of sync.
74
"""
75
76
class ProgrammingError(DatabaseError):
77
"""
78
Programming errors.
79
Examples: table not found, SQL syntax error, wrong parameter count.
80
"""
81
82
class NotSupportedError(DatabaseError):
83
"""
84
Errors when using API not supported by database.
85
Examples: unsupported SQL feature, method not implemented.
86
"""
87
```
88
89
## Usage Examples
90
91
### Basic Error Handling
92
93
```python
94
import phoenixdb
95
96
try:
97
conn = phoenixdb.connect('http://localhost:8765/')
98
cursor = conn.cursor()
99
cursor.execute("SELECT * FROM users")
100
results = cursor.fetchall()
101
except phoenixdb.Error as e:
102
print(f"Database error: {e.message}")
103
if e.code:
104
print(f"Error code: {e.code}")
105
if e.sqlstate:
106
print(f"SQL state: {e.sqlstate}")
107
if e.cause:
108
print(f"Caused by: {e.cause}")
109
```
110
111
### Specific Error Types
112
113
```python
114
import phoenixdb
115
116
try:
117
conn = phoenixdb.connect('http://invalid-url:8765/')
118
except phoenixdb.InterfaceError as e:
119
print(f"Connection interface error: {e.message}")
120
except phoenixdb.OperationalError as e:
121
print(f"Connection failed: {e.message}")
122
123
try:
124
cursor = conn.cursor()
125
cursor.execute("SELECT * FROM nonexistent_table")
126
except phoenixdb.ProgrammingError as e:
127
print(f"SQL programming error: {e.message}")
128
print(f"SQL state: {e.sqlstate}")
129
130
try:
131
cursor.execute("INSERT INTO users VALUES (?, ?)", (1,)) # Wrong parameter count
132
except phoenixdb.ProgrammingError as e:
133
print(f"Parameter error: {e.message}")
134
135
try:
136
cursor.execute("INSERT INTO users (id) VALUES (?)", ("not_a_number",))
137
except phoenixdb.DataError as e:
138
print(f"Data type error: {e.message}")
139
```
140
141
### Connection Errors
142
143
```python
144
import phoenixdb
145
146
try:
147
# Invalid URL format
148
conn = phoenixdb.connect('invalid://url')
149
except phoenixdb.InterfaceError as e:
150
print(f"Invalid connection parameters: {e.message}")
151
152
try:
153
# Server not available
154
conn = phoenixdb.connect('http://nonexistent-server:8765/')
155
except phoenixdb.OperationalError as e:
156
print(f"Cannot connect to server: {e.message}")
157
158
try:
159
# Authentication failure
160
conn = phoenixdb.connect('http://localhost:8765/',
161
authentication='BASIC',
162
avatica_user='wrong_user',
163
avatica_password='wrong_password')
164
except phoenixdb.OperationalError as e:
165
print(f"Authentication failed: {e.message}")
166
```
167
168
### Query Execution Errors
169
170
```python
171
import phoenixdb
172
173
conn = phoenixdb.connect('http://localhost:8765/')
174
cursor = conn.cursor()
175
176
try:
177
# SQL syntax error
178
cursor.execute("SELCT * FROM users") # Typo in SELECT
179
except phoenixdb.ProgrammingError as e:
180
print(f"SQL syntax error: {e.message}")
181
print(f"SQL state: {e.sqlstate}")
182
183
try:
184
# Table doesn't exist
185
cursor.execute("SELECT * FROM nonexistent_table")
186
except phoenixdb.ProgrammingError as e:
187
print(f"Table not found: {e.message}")
188
189
try:
190
# Column doesn't exist
191
cursor.execute("SELECT nonexistent_column FROM users")
192
except phoenixdb.ProgrammingError as e:
193
print(f"Column not found: {e.message}")
194
195
try:
196
# Division by zero
197
cursor.execute("SELECT 1/0")
198
except phoenixdb.DataError as e:
199
print(f"Data processing error: {e.message}")
200
```
201
202
### Parameter Errors
203
204
```python
205
import phoenixdb
206
207
conn = phoenixdb.connect('http://localhost:8765/')
208
cursor = conn.cursor()
209
210
try:
211
# Wrong number of parameters
212
cursor.execute("INSERT INTO users (id, name) VALUES (?, ?)", (1,)) # Missing parameter
213
except phoenixdb.ProgrammingError as e:
214
print(f"Parameter count mismatch: {e.message}")
215
216
try:
217
# Invalid parameter type for array
218
cursor.execute("INSERT INTO test_array (id, numbers) VALUES (?, ?)", (1, "not_an_array"))
219
except phoenixdb.ProgrammingError as e:
220
print(f"Invalid parameter type: {e.message}")
221
```
222
223
### Constraint Violations
224
225
```python
226
import phoenixdb
227
228
conn = phoenixdb.connect('http://localhost:8765/')
229
cursor = conn.cursor()
230
231
try:
232
# Create table with primary key
233
cursor.execute("CREATE TABLE test_pk (id INTEGER PRIMARY KEY, name VARCHAR)")
234
235
# Insert first row
236
cursor.execute("INSERT INTO test_pk VALUES (1, 'first')")
237
238
# Try to insert duplicate primary key
239
cursor.execute("INSERT INTO test_pk VALUES (1, 'duplicate')")
240
except phoenixdb.IntegrityError as e:
241
print(f"Primary key violation: {e.message}")
242
```
243
244
### Cursor State Errors
245
246
```python
247
import phoenixdb
248
249
conn = phoenixdb.connect('http://localhost:8765/')
250
cursor = conn.cursor()
251
252
try:
253
# Try to fetch without executing query
254
cursor.fetchone()
255
except phoenixdb.ProgrammingError as e:
256
print(f"No select statement executed: {e.message}")
257
258
# Close cursor
259
cursor.close()
260
261
try:
262
# Try to use closed cursor
263
cursor.execute("SELECT 1")
264
except phoenixdb.ProgrammingError as e:
265
print(f"Cursor is closed: {e.message}")
266
```
267
268
### Connection State Errors
269
270
```python
271
import phoenixdb
272
273
conn = phoenixdb.connect('http://localhost:8765/')
274
cursor = conn.cursor()
275
276
# Close connection
277
conn.close()
278
279
try:
280
# Try to use closed connection
281
cursor.execute("SELECT 1")
282
except phoenixdb.ProgrammingError as e:
283
print(f"Connection is closed: {e.message}")
284
285
try:
286
# Try to create cursor from closed connection
287
new_cursor = conn.cursor()
288
except phoenixdb.ProgrammingError as e:
289
print(f"Connection is closed: {e.message}")
290
```
291
292
### Error Context and Debugging
293
294
```python
295
import phoenixdb
296
import traceback
297
298
def handle_database_error(e):
299
"""Comprehensive error information display."""
300
print(f"Error Type: {type(e).__name__}")
301
print(f"Message: {e.message}")
302
303
if hasattr(e, 'code') and e.code is not None:
304
print(f"Error Code: {e.code}")
305
306
if hasattr(e, 'sqlstate') and e.sqlstate:
307
print(f"SQL State: {e.sqlstate}")
308
309
if hasattr(e, 'cause') and e.cause:
310
print(f"Underlying Cause: {e.cause}")
311
312
print("Traceback:")
313
traceback.print_exc()
314
315
try:
316
conn = phoenixdb.connect('http://localhost:8765/')
317
cursor = conn.cursor()
318
cursor.execute("INVALID SQL SYNTAX")
319
except phoenixdb.Error as e:
320
handle_database_error(e)
321
```
322
323
## Error Recovery Strategies
324
325
### Connection Recovery
326
327
```python
328
import phoenixdb
329
import time
330
331
def create_connection_with_retry(url, max_retries=3, delay=1):
332
"""Create connection with retry logic."""
333
for attempt in range(max_retries):
334
try:
335
return phoenixdb.connect(url)
336
except phoenixdb.OperationalError as e:
337
if attempt < max_retries - 1:
338
print(f"Connection attempt {attempt + 1} failed: {e.message}")
339
time.sleep(delay)
340
continue
341
else:
342
print(f"All connection attempts failed")
343
raise
344
345
# Usage
346
try:
347
conn = create_connection_with_retry('http://localhost:8765/')
348
except phoenixdb.OperationalError:
349
print("Could not establish connection after retries")
350
```
351
352
### Transaction Recovery
353
354
```python
355
import phoenixdb
356
357
def execute_with_rollback(conn, statements):
358
"""Execute statements with automatic rollback on error."""
359
cursor = conn.cursor()
360
try:
361
# Execute all statements
362
for sql, params in statements:
363
cursor.execute(sql, params)
364
365
# Commit if all successful
366
conn.commit()
367
print("All statements executed successfully")
368
369
except phoenixdb.DatabaseError as e:
370
# Rollback on any database error
371
print(f"Error occurred: {e.message}")
372
print("Rolling back transaction...")
373
conn.rollback()
374
raise
375
finally:
376
cursor.close()
377
378
# Usage
379
statements = [
380
("INSERT INTO users VALUES (?, ?)", (1, 'user1')),
381
("INSERT INTO users VALUES (?, ?)", (2, 'user2')),
382
("UPDATE users SET name = ? WHERE id = ?", ('updated', 1))
383
]
384
385
try:
386
execute_with_rollback(conn, statements)
387
except phoenixdb.DatabaseError:
388
print("Transaction failed and was rolled back")
389
```