Exceptions
KML ORM defines custom exceptions for handling various error conditions during KML parsing and querying operations.
Exception classes for KML ORM operations.
This module defines all custom exceptions used throughout the KML ORM package, following Django’s exception patterns for consistency.
- exception kmlorm.core.exceptions.KMLOrmException[source]
Bases:
ExceptionBase exception class for all KML ORM operations.
All other KML ORM exceptions inherit from this class, making it easy to catch any KML ORM-related error.
- exception kmlorm.core.exceptions.KMLParseError(message, source=None)[source]
Bases:
KMLOrmExceptionRaised when KML content cannot be parsed.
This exception is raised when: - KML file is malformed or invalid - Required KML elements are missing - KML content doesn’t conform to expected structure
- exception kmlorm.core.exceptions.KMLElementNotFound(element_type, query_kwargs=None)[source]
Bases:
KMLOrmExceptionRaised when a get() query finds no matching elements.
Similar to Django’s DoesNotExist exception, this is raised when a get() call expects exactly one element but finds none.
- exception kmlorm.core.exceptions.KMLMultipleElementsReturned(element_type, count, query_kwargs=None)[source]
Bases:
KMLOrmExceptionRaised when a get() query finds multiple matching elements.
Similar to Django’s MultipleObjectsReturned exception, this is raised when a get() call expects exactly one element but finds multiple.
- exception kmlorm.core.exceptions.KMLInvalidCoordinates(message, coordinates=None)[source]
Bases:
KMLOrmExceptionRaised when coordinates are invalid or out of range.
This exception is raised when: - Latitude is not between -90 and 90 - Longitude is not between -180 and 180 - Coordinate format is invalid - Required coordinate data is missing
- exception kmlorm.core.exceptions.KMLValidationError(message, field=None, value=None)[source]
Bases:
KMLOrmExceptionRaised when KML element validation fails.
This exception is raised when: - Required fields are missing - Field values don’t meet validation criteria - Cross-field validation fails
- exception kmlorm.core.exceptions.KMLQueryError(message, query_field=None)[source]
Bases:
KMLOrmExceptionRaised when a query cannot be executed.
This exception is raised when: - Invalid field names are used in queries - Invalid lookup types are specified - Query operations are not supported
Exception Hierarchy
All KML ORM exceptions inherit from KMLOrmException.
KMLOrmException
├── KMLParseError
├── KMLValidationError
├── KMLElementNotFound
├── KMLMultipleElementsReturned
├── KMLInvalidCoordinates
└── KMLQueryError
Base Exception
- exception kmlorm.core.exceptions.KMLOrmException[source]
Base exception class for all KML ORM operations.
All other KML ORM exceptions inherit from this class, making it easy to catch any KML ORM-related error.
Parsing Exceptions
Validation Exceptions
- exception kmlorm.core.exceptions.KMLValidationError(message, field=None, value=None)[source]
Raised when KML element validation fails.
This exception is raised when: - Required fields are missing - Field values don’t meet validation criteria - Cross-field validation fails
- exception kmlorm.core.exceptions.KMLInvalidCoordinates(message, coordinates=None)[source]
Raised when coordinates are invalid or out of range.
This exception is raised when: - Latitude is not between -90 and 90 - Longitude is not between -180 and 180 - Coordinate format is invalid - Required coordinate data is missing
Query Exceptions
- exception kmlorm.core.exceptions.KMLElementNotFound(element_type, query_kwargs=None)[source]
Raised when a get() query finds no matching elements.
Similar to Django’s DoesNotExist exception, this is raised when a get() call expects exactly one element but finds none.
- exception kmlorm.core.exceptions.KMLMultipleElementsReturned(element_type, count, query_kwargs=None)[source]
Raised when a get() query finds multiple matching elements.
Similar to Django’s MultipleObjectsReturned exception, this is raised when a get() call expects exactly one element but finds multiple.
Usage Examples
Handling Parse Errors
from kmlorm import KMLFile
from kmlorm.core.exceptions import KMLParseError
try:
kml = KMLFile.from_file('invalid.kml')
except KMLParseError as e:
print(f"Failed to parse KML: {e}")
Handling Query Errors
from kmlorm import KMLFile
from kmlorm.core.exceptions import KMLElementNotFound, KMLMultipleElementsReturned
kml = KMLFile.from_file('stores.kml')
try:
# This will raise KMLElementNotFound if no match
store = kml.placemarks.get(name='Nonexistent Store')
except KMLElementNotFound:
print("Store not found")
try:
# This will raise KMLMultipleElementsReturned if multiple matches
store = kml.placemarks.get(name__icontains='Capital')
except KMLMultipleElementsReturned:
print("Multiple stores found, be more specific")
Handling Validation Errors
from kmlorm.models.point import Coordinate
from kmlorm.core.exceptions import KMLValidationError
try:
# Invalid coordinates (validation happens automatically on creation)
coord = Coordinate(longitude=200, latitude=100) # Out of valid range
except KMLValidationError as e:
print(f"Validation failed: {e}")
print(f"Field: {e.field}")
print(f"Value: {e.value}")
Best Practices
Catch Specific Exceptions: Always catch the most specific exception type first.
Provide User-Friendly Messages: Convert technical exceptions into user-friendly error messages.
Log Errors: Log exceptions for debugging while showing clean messages to users.
import logging
from kmlorm import KMLFile
from kmlorm.core.exceptions import KMLParseError, KMLOrmException
logger = logging.getLogger(__name__)
def load_kml_safely(file_path):
try:
return KMLFile.from_file(file_path)
except KMLParseError as e:
logger.error(f"Failed to parse KML file {file_path}: {e}")
if hasattr(e, 'source') and e.source:
logger.error(f"Error source: {e.source}")
raise ValueError(f"Invalid KML file: {file_path}")
except KMLOrmException as e:
logger.error(f"KML ORM error with {file_path}: {e}")
raise
except Exception as e:
logger.error(f"Unexpected error loading {file_path}: {e}")
raise RuntimeError(f"Failed to load KML file: {file_path}")
Error Codes and Context
Many exceptions include additional context about the error:
Field name: Which field caused the validation error
Value: The invalid value that caused the error
Element context: Information about which KML element failed
from kmlorm.models.point import Coordinate
from kmlorm.core.exceptions import KMLValidationError
try:
# Example that shows error context
coord = Coordinate(longitude=200, latitude=100)
except KMLValidationError as e:
print(f"Field: {e.field if hasattr(e, 'field') else 'N/A'}")
print(f"Value: {e.value if hasattr(e, 'value') else 'N/A'}")
print(f"Message: {str(e)}")
# Exception attributes available for KMLElementNotFound:
try:
kml.placemarks.get(name='Missing')
except KMLElementNotFound as e:
print(f"Element type: {e.element_type}")
print(f"Query: {e.query_kwargs}")
# Exception attributes available for KMLMultipleElementsReturned:
try:
kml.placemarks.get(name__icontains='Store')
except KMLMultipleElementsReturned as e:
print(f"Element type: {e.element_type}")
print(f"Count found: {e.count}")
print(f"Query: {e.query_kwargs}")