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: Exception

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.

exception kmlorm.core.exceptions.KMLParseError(message, source=None)[source]

Bases: KMLOrmException

Raised 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

__init__(message, source=None)[source]

Initialize KMLParseError.

Parameters:
  • message (str) – Description of the parsing error

  • source (Optional[str]) – Optional source file or URL that caused the error

exception kmlorm.core.exceptions.KMLElementNotFound(element_type, query_kwargs=None)[source]

Bases: KMLOrmException

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.

__init__(element_type, query_kwargs=None)[source]

Initialize KMLElementNotFound.

Parameters:
  • element_type (str) – The type of element that was not found

  • query_kwargs (Optional[dict]) – The query parameters that yielded no results

exception kmlorm.core.exceptions.KMLMultipleElementsReturned(element_type, count, query_kwargs=None)[source]

Bases: KMLOrmException

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.

__init__(element_type, count, query_kwargs=None)[source]

Initialize KMLMultipleElementsReturned.

Parameters:
  • element_type (str) – The type of element that had multiple matches

  • count (int) – Number of elements found

  • query_kwargs (Optional[dict]) – The query parameters that yielded multiple results

exception kmlorm.core.exceptions.KMLInvalidCoordinates(message, coordinates=None)[source]

Bases: KMLOrmException

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

__init__(message, coordinates=None)[source]

Initialize KMLInvalidCoordinates.

Parameters:
  • message (str) – Description of what makes the coordinates invalid

  • coordinates (Optional[Any]) – The invalid coordinate data

exception kmlorm.core.exceptions.KMLValidationError(message, field=None, value=None)[source]

Bases: KMLOrmException

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

__init__(message, field=None, value=None)[source]

Initialize KMLValidationError.

Parameters:
  • message (str) – Description of the validation error

  • field (Optional[str]) – Name of the field that failed validation

  • value (Optional[Any]) – The invalid value

exception kmlorm.core.exceptions.KMLQueryError(message, query_field=None)[source]

Bases: KMLOrmException

Raised 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

__init__(message, query_field=None)[source]

Initialize KMLQueryError.

Parameters:
  • message (str) – Description of the query error

  • query_field (Optional[str]) – The field that caused the query error

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

exception kmlorm.core.exceptions.KMLParseError(message, source=None)[source]

Raised 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

__init__(message, source=None)[source]

Initialize KMLParseError.

Parameters:
  • message (str) – Description of the parsing error

  • source (Optional[str]) – Optional source file or URL that caused the error

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

__init__(message, field=None, value=None)[source]

Initialize KMLValidationError.

Parameters:
  • message (str) – Description of the validation error

  • field (Optional[str]) – Name of the field that failed validation

  • value (Optional[Any]) – The invalid value

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

__init__(message, coordinates=None)[source]

Initialize KMLInvalidCoordinates.

Parameters:
  • message (str) – Description of what makes the coordinates invalid

  • coordinates (Optional[Any]) – The invalid coordinate data

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.

__init__(element_type, query_kwargs=None)[source]

Initialize KMLElementNotFound.

Parameters:
  • element_type (str) – The type of element that was not found

  • query_kwargs (Optional[dict]) – The query parameters that yielded no results

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.

__init__(element_type, count, query_kwargs=None)[source]

Initialize KMLMultipleElementsReturned.

Parameters:
  • element_type (str) – The type of element that had multiple matches

  • count (int) – Number of elements found

  • query_kwargs (Optional[dict]) – The query parameters that yielded multiple results

exception kmlorm.core.exceptions.KMLQueryError(message, query_field=None)[source]

Raised 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

__init__(message, query_field=None)[source]

Initialize KMLQueryError.

Parameters:
  • message (str) – Description of the query error

  • query_field (Optional[str]) – The field that caused the query error

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

  1. Catch Specific Exceptions: Always catch the most specific exception type first.

  2. Provide User-Friendly Messages: Convert technical exceptions into user-friendly error messages.

  3. 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}")