0
# Exception Handling
1
2
Comprehensive error handling and exception classes for robust DDL parsing with detailed error reporting and debugging capabilities. The exception system provides clear error messages and maintains backward compatibility.
3
4
## Capabilities
5
6
### Base Exception Class
7
8
Primary exception class for all simple-ddl-parser related errors with comprehensive error information.
9
10
```python { .api }
11
class SimpleDDLParserException(Exception):
12
"""
13
Base exception for simple DDL parser library.
14
15
Raised when DDL parsing encounters errors such as:
16
- Invalid DDL syntax
17
- Unsupported SQL constructs
18
- Parsing conflicts or ambiguities
19
- File reading errors
20
- Configuration errors
21
22
Inherits from: Exception
23
"""
24
```
25
26
### Backward Compatibility Alias
27
28
Alias for the base exception class to maintain backward compatibility with older code.
29
30
```python { .api }
31
DDLParserError = SimpleDDLParserException
32
```
33
34
## Usage Examples
35
36
### Basic Exception Handling
37
38
```python
39
from simple_ddl_parser import DDLParser, SimpleDDLParserException
40
41
try:
42
parser = DDLParser("INVALID DDL SYNTAX")
43
result = parser.run()
44
except SimpleDDLParserException as e:
45
print(f"Parsing error: {e}")
46
```
47
48
### Using Backward Compatible Alias
49
50
```python
51
from simple_ddl_parser import DDLParser, DDLParserError
52
53
try:
54
parser = DDLParser(malformed_ddl)
55
result = parser.run()
56
except DDLParserError as e:
57
print(f"DDL parsing failed: {e}")
58
```
59
60
### Silent Mode vs Exception Mode
61
62
```python
63
from simple_ddl_parser import DDLParser
64
65
# Silent mode (default): Suppresses exceptions, returns partial results
66
parser = DDLParser(problematic_ddl, silent=True)
67
result = parser.run() # Returns what it could parse, no exception
68
69
# Non-silent mode: Raises exceptions on parsing errors
70
parser = DDLParser(problematic_ddl, silent=False)
71
try:
72
result = parser.run()
73
except SimpleDDLParserException as e:
74
print(f"Parsing failed with error: {e}")
75
```
76
77
### File Parsing Exception Handling
78
79
```python
80
from simple_ddl_parser import parse_from_file, SimpleDDLParserException
81
82
try:
83
result = parse_from_file("schema.sql", parser_settings={"silent": False})
84
except FileNotFoundError:
85
print("DDL file not found")
86
except SimpleDDLParserException as e:
87
print(f"DDL parsing error: {e}")
88
except UnicodeDecodeError:
89
print("File encoding error - try specifying encoding parameter")
90
```
91
92
### Comprehensive Error Handling
93
94
```python
95
from simple_ddl_parser import DDLParser, SimpleDDLParserException
96
import logging
97
98
# Configure logging for detailed error information
99
logging.basicConfig(level=logging.DEBUG)
100
101
def robust_ddl_parsing(ddl_content):
102
"""Robust DDL parsing with comprehensive error handling."""
103
104
try:
105
# Try with silent mode first for partial results
106
parser = DDLParser(ddl_content, silent=True, debug=True)
107
result = parser.run()
108
109
if not result:
110
# If no results, try non-silent mode for detailed error
111
parser = DDLParser(ddl_content, silent=False, debug=True)
112
result = parser.run()
113
114
return result
115
116
except SimpleDDLParserException as e:
117
print(f"DDL parsing failed: {e}")
118
return None
119
120
except Exception as e:
121
print(f"Unexpected error during DDL parsing: {e}")
122
return None
123
124
# Usage
125
parsed_data = robust_ddl_parsing(complex_ddl)
126
if parsed_data:
127
print("Parsing successful")
128
else:
129
print("Parsing failed - check logs for details")
130
```
131
132
## Common Error Scenarios
133
134
### Invalid DDL Syntax
135
136
```python
137
# This will raise SimpleDDLParserException in non-silent mode
138
invalid_ddl = "CREATE INVALID SYNTAX"
139
140
parser = DDLParser(invalid_ddl, silent=False)
141
try:
142
result = parser.run()
143
except SimpleDDLParserException:
144
print("Invalid DDL syntax detected")
145
```
146
147
### Unsupported SQL Constructs
148
149
```python
150
# Some advanced SQL features might not be supported
151
advanced_ddl = """
152
CREATE TABLE test (
153
id INT,
154
data JSON CHECK (JSON_VALID(data)) -- Complex check constraint
155
);
156
"""
157
158
parser = DDLParser(advanced_ddl, silent=False)
159
try:
160
result = parser.run()
161
except SimpleDDLParserException as e:
162
print(f"Unsupported SQL construct: {e}")
163
```
164
165
### Configuration Errors
166
167
```python
168
try:
169
# Invalid log level
170
parser = DDLParser(ddl, log_level="INVALID_LEVEL")
171
except (ValueError, SimpleDDLParserException) as e:
172
print(f"Configuration error: {e}")
173
```
174
175
## Debugging with Exceptions
176
177
### Enable Debug Mode for Better Error Messages
178
179
```python
180
from simple_ddl_parser import DDLParser
181
182
# Enable debug mode for detailed error information
183
parser = DDLParser(
184
problematic_ddl,
185
silent=False,
186
debug=True,
187
log_file="parser_debug.log",
188
log_level="DEBUG"
189
)
190
191
try:
192
result = parser.run()
193
except SimpleDDLParserException as e:
194
print(f"Detailed error: {e}")
195
# Check parser_debug.log for additional context
196
```
197
198
### Exception Chaining
199
200
```python
201
def parse_schema_files(file_list):
202
"""Parse multiple schema files with error aggregation."""
203
results = []
204
errors = []
205
206
for file_path in file_list:
207
try:
208
result = parse_from_file(file_path, parser_settings={"silent": False})
209
results.append({"file": file_path, "data": result})
210
except SimpleDDLParserException as e:
211
errors.append({"file": file_path, "error": str(e)})
212
213
if errors:
214
error_summary = "; ".join([f"{err['file']}: {err['error']}" for err in errors])
215
raise SimpleDDLParserException(f"Multiple parsing errors: {error_summary}")
216
217
return results
218
```
219
220
## Best Practices
221
222
### Gradual Error Handling
223
224
1. **Start with silent mode** to get partial results
225
2. **Switch to non-silent mode** if no results for detailed errors
226
3. **Enable debug mode** for complex parsing issues
227
4. **Use logging** to capture detailed parsing information
228
229
### Production Error Handling
230
231
```python
232
import logging
233
from simple_ddl_parser import DDLParser, SimpleDDLParserException
234
235
logger = logging.getLogger(__name__)
236
237
def production_ddl_parse(ddl_content, strict=False):
238
"""Production-ready DDL parsing with proper error handling."""
239
240
try:
241
parser = DDLParser(
242
ddl_content,
243
silent=not strict, # Silent mode unless strict parsing required
244
log_level=logging.WARNING
245
)
246
247
result = parser.run()
248
249
if not result and not strict:
250
logger.warning("DDL parsing returned no results")
251
252
return result
253
254
except SimpleDDLParserException as e:
255
logger.error(f"DDL parsing failed: {e}")
256
if strict:
257
raise # Re-raise in strict mode
258
return None
259
260
except Exception as e:
261
logger.error(f"Unexpected parsing error: {e}")
262
raise # Always re-raise unexpected errors
263
```