0
# Exception Handling
1
2
Comprehensive exception classes for error handling in neomodel operations. These exceptions provide detailed information about various error conditions that can occur during database operations, model definitions, and data validation.
3
4
## Capabilities
5
6
### Base Exceptions
7
8
Base exception classes that serve as the foundation for all neomodel-specific errors.
9
10
```python { .api }
11
class NeomodelException(Exception):
12
"""
13
Base class that identifies all exceptions raised by neomodel.
14
"""
15
16
class ConstraintValidationFailed(ValueError, NeomodelException):
17
"""
18
Raised when database constraint validation fails.
19
20
Args:
21
msg (str): Error message describing the constraint violation
22
"""
23
def __init__(self, msg: str): ...
24
```
25
26
### Query and Retrieval Exceptions
27
28
Exceptions that occur during node and relationship retrieval operations.
29
30
```python { .api }
31
class DoesNotExist(NeomodelException):
32
"""
33
Raised when a requested node or relationship does not exist.
34
35
Args:
36
msg (str): Error message describing what was not found
37
"""
38
def __init__(self, msg: str): ...
39
40
class MultipleNodesReturned(ValueError, NeomodelException):
41
"""
42
Raised when multiple nodes are returned for a query expecting a single result.
43
44
Args:
45
msg (str): Error message describing the multiple results
46
"""
47
def __init__(self, msg: str): ...
48
49
class NotConnected(NeomodelException):
50
"""
51
Raised when nodes are not connected as expected for a relationship operation.
52
53
Args:
54
action (str): The action that was attempted
55
node1: First node in the attempted relationship
56
node2: Second node in the attempted relationship
57
"""
58
def __init__(self, action: str, node1, node2): ...
59
```
60
61
### Property Validation Exceptions
62
63
Exceptions related to property validation and data type conversion.
64
65
```python { .api }
66
class RequiredProperty(NeomodelException):
67
"""
68
Raised when a required property is not provided.
69
70
Args:
71
key (str): Property name that is required
72
cls: Node class that requires the property
73
"""
74
def __init__(self, key: str, cls): ...
75
76
class UniqueProperty(ConstraintValidationFailed):
77
"""
78
Raised when a unique constraint violation occurs.
79
80
Args:
81
msg (str): Error message describing the unique constraint violation
82
"""
83
def __init__(self, msg: str): ...
84
85
class InflateError(ValueError, NeomodelException):
86
"""
87
Raised when converting database values to Python objects fails.
88
89
Args:
90
key (str): Property name causing the error
91
cls: Node class being inflated
92
msg (str): Error message
93
obj (optional): Object that caused the error
94
"""
95
def __init__(self, key: str, cls, msg: str, obj=None): ...
96
97
class DeflateError(ValueError, NeomodelException):
98
"""
99
Raised when converting Python objects to database values fails.
100
101
Args:
102
key (str): Property name causing the error
103
cls: Node class being deflated
104
msg (str): Error message
105
obj: Object that caused the error
106
"""
107
def __init__(self, key: str, cls, msg: str, obj): ...
108
109
class InflateConflict(NeomodelException):
110
"""
111
Raised when property inflation results in conflicting values.
112
113
Args:
114
cls: Node class with conflicting property
115
key (str): Property name in conflict
116
value: Conflicting value
117
nid (str): Node ID with the conflict
118
"""
119
def __init__(self, cls, key: str, value, nid: str): ...
120
121
class DeflateConflict(InflateConflict):
122
"""
123
Raised when property deflation results in conflicting values.
124
125
Args:
126
cls: Node class with conflicting property
127
key (str): Property name in conflict
128
value: Conflicting value
129
nid (str): Node ID with the conflict
130
"""
131
def __init__(self, cls, key: str, value, nid: str): ...
132
```
133
134
### Cardinality Exceptions
135
136
Exceptions related to relationship cardinality constraint violations.
137
138
```python { .api }
139
class AttemptedCardinalityViolation(NeomodelException):
140
"""
141
Raised when attempting to violate cardinality constraints.
142
143
Example: A relationship of type One trying to connect a second node.
144
"""
145
146
class CardinalityViolation(NeomodelException):
147
"""
148
Raised when database state doesn't match cardinality definitions.
149
150
Example: A relationship type OneOrMore returns no nodes.
151
152
Args:
153
rel_manager: Relationship manager with cardinality constraint
154
actual: Actual number of relationships found
155
"""
156
def __init__(self, rel_manager, actual): ...
157
```
158
159
### Model Definition Exceptions
160
161
Exceptions that occur during model class definition and registration.
162
163
```python { .api }
164
class ModelDefinitionException(NeomodelException):
165
"""
166
Base exception for node-to-class registry errors.
167
168
Args:
169
db_node_rel_class: Database node or relationship class causing the error
170
current_node_class_registry (dict): Current node class registry
171
current_db_specific_node_class_registry (dict): Database-specific registry
172
"""
173
def __init__(
174
self,
175
db_node_rel_class,
176
current_node_class_registry: dict,
177
current_db_specific_node_class_registry: dict,
178
): ...
179
180
class NodeClassNotDefined(ModelDefinitionException):
181
"""
182
Raised when unable to resolve a Neo4j Node to a data model object.
183
184
This occurs when query results contain nodes with labels that don't
185
match any imported class definitions.
186
"""
187
188
class NodeClassAlreadyDefined(ModelDefinitionException):
189
"""
190
Raised when attempting to re-map labels to an already registered class.
191
"""
192
193
class RelationshipClassNotDefined(ModelDefinitionException):
194
"""
195
Raised when unable to resolve a Neo4j Relationship to a data model object.
196
"""
197
198
class RelationshipClassRedefined(ModelDefinitionException):
199
"""
200
Raised when attempting to re-map a relationship label to a different type.
201
202
Args:
203
db_rel_class_type: Relationship type causing the error
204
current_node_class_registry (dict): Current node class registry
205
current_db_specific_node_class_registry (dict): Database-specific registry
206
remapping_to_class: Class the relationship was attempted to be redefined to
207
"""
208
def __init__(
209
self,
210
db_rel_class_type,
211
current_node_class_registry: dict,
212
current_db_specific_node_class_registry: dict,
213
remapping_to_class,
214
): ...
215
```
216
217
### Feature Support Exceptions
218
219
Exceptions for unsupported features or operations.
220
221
```python { .api }
222
class FeatureNotSupported(NeomodelException):
223
"""
224
Raised when a requested feature is not supported.
225
226
Args:
227
msg (str): Error message describing the unsupported feature
228
"""
229
def __init__(self, msg: str): ...
230
```
231
232
## Usage Examples
233
234
### Basic Exception Handling
235
236
```python
237
from neomodel import StructuredNode, StringProperty, DoesNotExist, UniqueProperty
238
239
class Person(StructuredNode):
240
name = StringProperty(unique_index=True, required=True)
241
242
# Handle node not found
243
try:
244
person = Person.nodes.get(name="John")
245
except DoesNotExist:
246
print("Person not found")
247
248
# Handle unique constraint violation
249
try:
250
Person(name="Alice").save()
251
Person(name="Alice").save() # Will raise UniqueProperty
252
except UniqueProperty as e:
253
print(f"Unique constraint violated: {e.message}")
254
```
255
256
### Cardinality Exception Handling
257
258
```python
259
from neomodel import (
260
StructuredNode, StringProperty, RelationshipTo,
261
One, CardinalityViolation
262
)
263
264
class Person(StructuredNode):
265
name = StringProperty()
266
spouse = RelationshipTo('Person', 'MARRIED_TO', cardinality=One)
267
268
person = Person(name="John").save()
269
270
# Handle cardinality violation
271
try:
272
spouses = person.spouse.all() # Will raise if no spouse exists
273
except CardinalityViolation as e:
274
print(f"Cardinality constraint violated: {e}")
275
```
276
277
### Property Validation Exception Handling
278
279
```python
280
from neomodel import (
281
StructuredNode, IntegerProperty,
282
RequiredProperty, InflateError
283
)
284
285
class Product(StructuredNode):
286
name = StringProperty(required=True)
287
price = IntegerProperty()
288
289
# Handle required property missing
290
try:
291
Product(price=100).save() # Missing required 'name'
292
except RequiredProperty as e:
293
print(f"Required property missing: {e.property_name}")
294
295
# Handle property inflation error
296
try:
297
# Assuming database contains invalid data for price property
298
product = Product.nodes.get(name="Widget")
299
except InflateError as e:
300
print(f"Error inflating property '{e.property_name}': {e.msg}")
301
```