Skip to main content
The AveniECA API returns structured error responses and HTTP status codes to help you handle failures gracefully.

Error Response Model

When an error occurs, the API returns an Error object:
from avenieca.api.model import Error

@dataclass
class Error(Base):
    errors: List[str]  # List of error messages

Response Pattern

All API methods return a tuple of (response, status_code):
response, status = eca.ess.get_one(module_id="example", db_id=1)

if status == 200:
    # Success - response is the expected model
    print(f"ESS ID: {response.id}")
else:
    # Error - response is an Error object or raw response
    if isinstance(response, Error):
        print(f"Errors: {response.errors}")
    else:
        print(f"Error: {response}")

HTTP Status Codes

Success Codes

  • 200 OK - Request succeeded (GET, PATCH, PUT)
  • 201 Created - Resource created successfully (POST)

Error Codes

  • 400 Bad Request - Invalid request parameters or data
  • 401 Unauthorized - Authentication failed or missing
  • 404 Not Found - Resource not found
  • 500 Internal Server Error - Server error

Common Errors

Authentication Errors

import os
from avenieca.api.eca import ECA
from avenieca.api.model import Config

config = Config(
    uri="http://localhost:2580/v1",
    username="invalid",
    password="wrong"
)

try:
    eca = ECA(config)
except Exception as e:
    print(f"Authentication failed: {e}")
    # Handle authentication failure

Resource Not Found

res, status = eca.ess.get_one(module_id="example", db_id=999999)

if status == 404:
    print("ESS not found")
    # Handle missing resource
elif status == 200:
    print(f"Found ESS: {res.id}")

Invalid Data

from avenieca.api.model import ESSInsert, Error

# Missing required fields
incomplete_ess = ESSInsert(
    module_id="",  # Invalid empty module_id
    state=[],
    valence=0.0
)

res, status = eca.ess.create(data=incomplete_ess)

if status != 201:
    if isinstance(res, Error):
        print("Validation errors:")
        for error in res.errors:
            print(f"  - {error}")

Aggregate Errors

When creating or updating aggregates, you may receive an AggregateError:
from avenieca.api.model import AggregateError, Error

res, status = eca.ess.create(data=aggregate_ess)

if status != 201:
    if isinstance(res, AggregateError):
        print("Aggregate validation errors:")
        if res.field_length_errors:
            print(f"Field length errors: {res.field_length_errors}")
        if res.module_id_position:
            print(f"Module ID position errors: {res.module_id_position}")
        if res.invalid_ess_db_ids:
            print(f"Invalid ESS IDs: {res.invalid_ess_db_ids}")
    elif isinstance(res, Error):
        print(f"Errors: {res.errors}")

Error Handling Patterns

Basic Pattern

def safe_create_ess(eca, ess_data):
    """Safely create ESS with error handling."""
    res, status = eca.ess.create(data=ess_data)
    
    if status == 201:
        return res
    else:
        if isinstance(res, Error):
            raise ValueError(f"Failed to create ESS: {res.errors}")
        else:
            raise ValueError(f"Unexpected error: {res}")

try:
    ess = safe_create_ess(eca, ess_data)
    print(f"Created ESS {ess.id}")
except ValueError as e:
    print(f"Error: {e}")

Retry Pattern

import time
from typing import Optional

def get_ess_with_retry(
    eca,
    module_id: str,
    db_id: int,
    max_retries: int = 3
) -> Optional[ESSResponse]:
    """Get ESS with retry logic."""
    for attempt in range(max_retries):
        res, status = eca.ess.get_one(module_id=module_id, db_id=db_id)
        
        if status == 200:
            return res
        elif status == 404:
            return None  # Resource doesn't exist
        elif status >= 500:
            # Server error - retry
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # Exponential backoff
                continue
        else:
            # Client error - don't retry
            return None
    
    return None

ress = get_ess_with_retry(eca, "air_conditioner", 1)
if ess:
    print(f"Retrieved ESS {ess.id}")
else:
    print("Failed to retrieve ESS")

Validation Pattern

from avenieca.api.model import ESSInsert, Error

def validate_and_create_ess(eca, ess_data: ESSInsert):
    """Validate ESS data before creation."""
    # Pre-validation
    if not ess_data.module_id:
        raise ValueError("module_id is required")
    if not ess_data.state:
        raise ValueError("state cannot be empty")
    
    # Create
    res, status = eca.ess.create(data=ess_data)
    
    # Handle response
    if status == 201:
        return res
    elif isinstance(res, Error):
        raise ValueError(f"API errors: {', '.join(res.errors)}")
    else:
        raise ValueError(f"Unexpected error (status {status})")

try:
    ess = validate_and_create_ess(eca, ess_data)
    print(f"Created ESS {ess.id}")
except ValueError as e:
    print(f"Validation failed: {e}")

Best Practices

  1. Always check status codes - Don’t assume success
  2. Handle specific errors - Use isinstance() to check error types
  3. Log errors - Record errors for debugging
  4. Validate input - Check data before sending to API
  5. Use retries for server errors - Implement exponential backoff
  6. Don’t retry client errors - 4xx errors won’t succeed on retry
  7. Provide user feedback - Convert errors to user-friendly messages

Complete Example

import os
import logging
from avenieca.api.eca import ECA
from avenieca.api.model import Config, ESSInsert, Error, AggregateError

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize client with error handling
try:
    config = Config(
        uri="http://localhost:2580/v1",
        username=os.getenv("USERNAME"),
        password=os.getenv("PASSWORD")
    )
    eca = ECA(config)
    logger.info("Successfully initialized ECA client")
except Exception as e:
    logger.error(f"Failed to initialize ECA: {e}")
    raise

# Create ESS with comprehensive error handling
ess_data = ESSInsert(
    module_id="air_conditioner",
    state=[25.0],
    valence=10.0,
    score=5
)

res, status = eca.ess.create(data=ess_data)

if status == 201:
    logger.info(f"Created ESS {res.id}")
    print(f"Success: ESS {res.id} created")
elif isinstance(res, AggregateError):
    logger.error(f"Aggregate validation failed: {res.__dict__}")
    print("Aggregate validation errors - check logs")
elif isinstance(res, Error):
    logger.error(f"API errors: {res.errors}")
    print(f"Failed: {', '.join(res.errors)}")
else:
    logger.error(f"Unexpected error (status {status}): {res}")
    print(f"Failed with status {status}")

Build docs developers (and LLMs) love