Exceptions¶
This module defines custom exception classes used throughout SurrealEngine.
Core Exceptions¶
- class surrealengine.exceptions.DoesNotExist[source]¶
Bases:
SurrealEngineErrorRaised when a document does not exist in the database.
This exception is raised when attempting to retrieve a document that does not exist in the database, such as when using the get() method with a query that matches no documents.
- class surrealengine.exceptions.MultipleObjectsReturned[source]¶
Bases:
SurrealEngineErrorRaised when multiple documents are returned when only one was expected.
This exception is raised when a query that is expected to return a single document returns multiple documents, such as when using the get() method with a query that matches multiple documents.
- class surrealengine.exceptions.ValidationError(message, errors=None, field_name=None)[source]¶
Bases:
SurrealEngineErrorRaised when document validation fails.
This exception is raised when a document fails validation, such as when a required field is missing or a field value is of the wrong type.
- errors¶
Dictionary of validation errors by field
- field_name¶
Name of the field that failed validation, if applicable
Usage Examples¶
Handling DoesNotExist¶
from surrealengine.exceptions import DoesNotExist
try:
user = await User.objects.get(id="nonexistent")
except DoesNotExist:
print("User not found")
Handling MultipleObjectsReturned¶
from surrealengine.exceptions import MultipleObjectsReturned
try:
user = await User.objects.get(age=25) # Multiple users with age 25
except MultipleObjectsReturned:
print("Multiple users found, use filter() instead")
Handling ValidationError¶
from surrealengine.exceptions import ValidationError
try:
user = User(email="invalid-email")
await user.save()
except ValidationError as e:
print(f"Validation failed: {e}")
Custom Exception Handling¶
from surrealengine.exceptions import DoesNotExist, ValidationError
async def safe_create_user(name, email):
try:
# Check if user already exists
existing_user = await User.objects.get(email=email)
return existing_user, False # User exists
except DoesNotExist:
try:
# Create new user
user = User(name=name, email=email)
await user.save()
return user, True # User created
except ValidationError as e:
print(f"Failed to create user: {e}")
return None, False