Error Handling

Error Handling

Not available on hosted execution yet: ctx.mcp is not wired on any hosted execution path (REST, MCP, scheduled runs or pipeline stages), so a command that calls it fails with IntegrationError. Tracked in #1943. Do not rely on it in a pack you publish.

This guide covers error handling patterns for Intelligence Pack development, including the SDK exception hierarchy, retry behavior, and best practices.

SDK Exception Hierarchy

The SDK provides a structured exception hierarchy for consistent error handling:

HuitzoError (base)
├── CommandError              # General command failure
├── ValidationError           # Input validation failures
├── CommandTimeoutError       # Command exceeded timeout
├── StorageError              # Storage operations failed
├── SecretsError              # User secret access failures
├── ExternalAPIError          # User-configured external API failures
├── IntegrationError          # Platform service failures
│   ├── IntegrationConnectionError  # (Proposed) Connection pool exhausted, DNS failure
│   ├── IntegrationAuthError        # (Proposed) Invalid credentials, expired token
│   ├── IntegrationTimeoutError     # (Proposed) External service did not respond
│   ├── IntegrationRateLimitError   # (Proposed) External service rate limit hit
│   ├── LLMError              # LLM provider errors
│   ├── CronError             # Cron scheduling errors
│   ├── EmailError            # Email sending errors
│   └── HTTPError             # HTTP request errors
├── HTTPSecurityError         # ctx.http refused a URL or a redirect hop (allowlist, HTTPS, internal address)
├── SSHError                  # SSH execution or connection failures
├── MCPError                  # MCP server failures
│   ├── MCPConnectionError    # Server unreachable
│   ├── MCPToolError          # Tool execution failed
│   ├── MCPTimeoutError       # Timeout exceeded
│   └── MCPSchemaError        # Invalid arguments
├── PipelineError             # Pipeline execution failures (fail-fast, scrubbed partial_results)
├── EventError                # (Proposed) Event bus failures
├── VFSError                  # (Proposed) Virtual file system failures
│   ├── MountError            # (Proposed) Mount point configuration failure
│   └── VFSFileNotFoundError  # (Proposed) File not found in mounted driver
├── PackExecutionError        # Cross-pack execution failed
├── PackPermissionError       # Insufficient permissions
├── ConfigurationError        # Invalid configuration
└── RateLimitError            # Rate limit exceeded

(Proposed) entries are architecturally specified but not yet implemented. See Component Model, Event Bus, and Virtual File System.

Importing Exceptions

from huitzo_sdk.errors import (
    HuitzoError,
    CommandError,
    ValidationError,
    CommandTimeoutError,
    StorageError,
    SecretsError,
    ExternalAPIError,
    IntegrationError,
    LLMError,
    CronError,
    EmailError,
    HTTPError,
    HTTPSecurityError,
    SSHError,
    MCPError,
    MCPConnectionError,
    MCPToolError,
    MCPTimeoutError,
    MCPSchemaError,
    PackExecutionError,
    PackPermissionError,
    PipelineError,
    ConfigurationError,
    RateLimitError,
)

Exception Reference

ValidationError

Raised when command input validation fails.

from huitzo_sdk.errors import ValidationError

@command("process", namespace="data")
async def process(args: ProcessArgs, ctx: Context) -> dict:
    if args.count < 0:
        raise ValidationError(
            field="count",
            value=args.count,
            message="Count must be non-negative"
        )

    if args.start_date > args.end_date:
        raise ValidationError(
            field="date_range",
            value=f"{args.start_date} - {args.end_date}",
            message="Start date must be before end date"
        )

Attributes: - field - The field that failed validation - value - The invalid value - message - Human-readable error message

CommandError

Raised when a command fails due to a general execution error. This is the catch-all error for command failures that don't fit into more specific categories.

from huitzo_sdk.errors import CommandError

@command("execute", namespace="tasks")
async def execute(args: Args, ctx: Context) -> dict:
    try:
        result = await perform_action()
    except SomeLibraryError as e:
        raise CommandError(
            message=f"Failed to execute action: {e}",
            exit_code=1,
            details={"original_error": str(e)}
        )
    return result

Attributes: - message - Human-readable error message - exit_code - Optional exit code for CLI contexts (default: 1) - details - Optional dictionary of additional context

CommandTimeoutError

Raised when a command exceeds its configured timeout.

from huitzo_sdk.errors import CommandTimeoutError

# SDK raises this automatically, but you can catch it:
@command("long-task", namespace="tasks", timeout=60)
async def long_task(args: Args, ctx: Context) -> dict:
    try:
        result = await slow_operation()
    except CommandTimeoutError:
        # Save partial progress
        await ctx.storage.save("partial-result", partial_data)
        raise  # Re-raise for platform handling

Attributes: - timeout_seconds - The configured timeout - elapsed_seconds - Actual elapsed time

StorageError

Raised when storage operations fail.

from huitzo_sdk.errors import StorageError

@command("save-data", namespace="data")
async def save_data(args: Args, ctx: Context) -> dict:
    try:
        await ctx.storage.save("key", large_data)
    except StorageError as e:
        ctx.log.error(f"Storage failed: {e.message}")
        raise

Attributes: - operation - The failed operation (for example get, save, delete or list on ctx.storage; read, write, copy, move, info, get_url or connect on ctx.files) - key - The storage key involved - message - Error details

SecretsError

Raised when a required user secret is missing or inaccessible. User secrets are per-user API keys declared in the pack manifest and provided by end users.

from huitzo_sdk.errors import SecretsError

@command("sync-data", namespace="finance")
async def sync_data(args: Args, ctx: Context) -> dict:
    try:
        api_key = await ctx.secrets.require("FINANCIAL_API_KEY")
    except SecretsError as e:
        # Return helpful guidance to the user
        return {
            "error": "Missing API key",
            "help": "Add this key on the Integrations page (+ Add integration → Secret value)",
            "secret_name": e.secret_name
        }

    # Use the secret...
    return await fetch_financial_data(api_key)

Attributes: - secret_name - The name of the missing secret - message - Human-readable error message

Related: See Secrets Management for the three-tier secrets model.

ExternalAPIError

Raised when an external API call fails due to invalid credentials or API errors. Use this for user-configured external services (accessed via user secrets) to provide clear feedback.

from huitzo_sdk.errors import ExternalAPIError

@command("fetch-accounts", namespace="finance")
async def fetch_accounts(args: Args, ctx: Context) -> dict:
    api_key = await ctx.secrets.require("PLAID_API_KEY")

    try:
        response = await ctx.http.get(
            "https://api.plaid.com/accounts",
            headers={"Authorization": f"Bearer {api_key}"}
        )
    except HTTPError as e:
        if e.status_code == 401:
            raise ExternalAPIError(
                service="plaid",
                message="Invalid API key. Verify it on the Integrations page."
            )
        if e.status_code == 403:
            raise ExternalAPIError(
                service="plaid",
                message="API key lacks required permissions. Check your Plaid dashboard."
            )
        raise

    return response

Attributes: - service - The external service name (e.g., "plaid", "stripe") - message - User-friendly error message with guidance

When to Use: - User's API key is invalid or expired - User's API key lacks required permissions - External service rate limits user's account - External service returns authentication errors

Related: See Secrets Management for user secrets patterns.

IntegrationError

Base class for external service failures. Use specific subclasses when possible.

A caller is told An integration call failed., never this class's message, because the platform raises it with upstream text in the message (see Error Response Format). Raise ExternalAPIError when the caller should read your text.

The platform also raises it with service="secrets" when a declared secret is configured but unresolvable — an ambiguous configuration, or a value that fails to decrypt. That one is reachable from ctx.secrets.get() and .exists() as well as .require(), which otherwise never raise for a missing value. See IntegrationError from ctx.secrets.

from huitzo_sdk.errors import IntegrationError, LLMError, HTTPError

@command("analyze", namespace="ai")
async def analyze(args: Args, ctx: Context) -> dict:
    try:
        response = await ctx.llm.complete(prompt)
    except LLMError as e:
        ctx.log.error(f"LLM failed: {e.provider} - {e.message}")
        raise IntegrationError(
            service="analysis",
            message="AI analysis unavailable"
        )

LLMError Attributes: - provider - LLM provider (openai, anthropic) - model - Model that failed - status_code - HTTP status code if applicable - message - platform-written text that never echoes the provider's response body, the raw transport error or the model's output; those go to the server log only, credentials redacted (see Error message hygiene)

HTTPError Attributes: - url - Request URL - method - HTTP method - status_code - Response status code - response_body - Response body (truncated)

HTTPSecurityError

Raised before a request is sent when ctx.http refuses its URL. For example: a host off the allowlist, a non-HTTPS URL, a cloud-metadata host, a host that resolves to a private address, or a URL with no valid hostname. Every redirect hop is checked the same way, so the refused URL can be one a redirect led to (Redirects).

HTTPSecurityError Attributes: - domain - The refused host, a redirect target's included - allowed_domains - The allowlist, when the host was refused for being off it

SSHError

Raised when an SSH connection or command execution fails. This covers connection failures, host key mismatches, target not found, command validation errors, and timeouts.

from huitzo_sdk.errors import SSHError

@command("run-task", namespace="compute")
async def run_task(args: Args, ctx: Context) -> dict:
    try:
        result = await ctx.ssh.run("gpu-cluster", args.command, timeout=60)
        return {"output": result.stdout, "exit_code": result.exit_code}
    except SSHError as e:
        ctx.log.error(f"SSH failed on {e.target}: {e.message}")
        return {"error": e.message, "target": e.target}

Attributes: - host - Hostname or IP of the target (may be empty if target not resolved) - target - Name of the SSH target that was requested - message - Human-readable error description

Common Causes: - Target not in pack's allowed list (ssh_targets.allowed in manifest) - Target not registered by the user - No host key fingerprint stored (needs /verify first) - Connection refused, timeout, or authentication failure - Command exceeds 4,096 byte limit or contains null bytes

Error Properties: - code = "SSH_ERROR" - http_status = 502 - retryable = True

Related: See SSH Integration for ctx.ssh API documentation.

MCPError

Base class for MCP (Model Context Protocol) server failures. Use specific subclasses for more precise error handling.

from huitzo_sdk.errors import (
    MCPError,
    MCPConnectionError,
    MCPToolError,
    MCPTimeoutError,
    MCPSchemaError
)

@command("github-issue", namespace="devtools")
async def github_issue(args: Args, ctx: Context) -> dict:
    try:
        result = await ctx.mcp.call("github", "create_issue", {
            "owner": args.owner,
            "repo": args.repo,
            "title": args.title
        })
        return {"issue": result}

    except MCPConnectionError as e:
        ctx.log.error(f"GitHub MCP server unavailable: {e.message}")
        return {"error": "GitHub integration temporarily unavailable", "retry": True}

    except MCPSchemaError as e:
        ctx.log.error(f"Invalid arguments: {e.message}")
        return {"error": f"Invalid input: {e.field}", "validation_errors": e.errors}

    except MCPToolError as e:
        ctx.log.error(f"GitHub tool failed: {e.message}")
        return {"error": f"GitHub error: {e.message}", "code": e.code}

    except MCPTimeoutError as e:
        ctx.log.error(f"GitHub call timed out after {e.timeout}s")
        return {"error": "Request timed out", "retry": True}

MCPConnectionError

Raised when the MCP server cannot be reached or crashes.

Attributes: - server - Name of the MCP server that failed to connect - message - Human-readable error description

Common Causes: - Server process crashed or failed to start - Network issues (for HTTP transport) - Invalid command configuration (for STDIO transport) - Missing or invalid environment variables

MCPToolError

Raised when an MCP tool execution fails.

Attributes: - server - MCP server name - tool - Tool name that failed - code - Error code from the MCP server - message - Error message from the tool

Common Causes: - Tool returned an error (e.g., GitHub API returned 404) - Tool doesn't exist on the server - Permission denied by external service

MCPTimeoutError

Raised when an MCP tool execution exceeds the configured timeout.

Attributes: - server - MCP server name - tool - Tool name that timed out - timeout - Configured timeout value in seconds

Solutions: - Increase timeout in the ctx.mcp.call() call - Check if the operation is genuinely slow - Consider breaking into smaller operations

MCPSchemaError

Raised when arguments don't match the tool's JSON Schema.

Attributes: - server - MCP server name - tool - Tool name - field - Field that failed validation - errors - List of validation error details - message - Human-readable validation message

Common Causes: - Missing required field - Wrong field type (e.g., string instead of number) - Value doesn't match pattern or constraints

Related: See MCP Reference for complete MCP API documentation.

PipelineError

Raised by the pipeline executor when a stage fails. Pipelines are fail-fast: the first failing stage halts the run, downstream stages are skipped, and the executor wraps the failure in a single PipelineError carrying per-stage telemetry. See Piping Protocol — Error Propagation for the protocol contract.

# pseudocode — handling a pipeline failure from a programmatic caller

from huitzo_sdk.errors import PipelineError

try:
    result = await run_pipeline(definition, initial_args)
except PipelineError as exc:
    failed = exc.partial_results[exc.failed_stage_index]
    log.error(
        "pipeline failed",
        stage=exc.failed_stage_name,
        stage_index=exc.failed_stage_index,
        error=failed.error,  # scrubbed dict — safe to surface
    )

Attributes: - failed_stage_index (int) — position of the stage that raised; -1 if the pipeline itself timed out. - failed_stage_name (str | None) — stage name, when applicable. - partial_results (list[StageResult]) — every stage that ran, including the failing one. A failed stage's error.message is the stage exception's safe text (its caller-facing text for an SDK error, a pydantic failure's rule summary, a platform-written refusal's own text (credentials redacted), or for any other exception a fixed sentence naming its class, <class>: the command failed; its message is not stored), never its raw str(); see Error message hygiene. Sensitive keys (api_key, token, password, secret, credential, auth) are recursively scrubbed from each stage's error payload before they cross the trust boundary. - original_error (Exception | None) — the underlying exception, when available, for raise … from chaining.

PipelineError.code is "PIPELINE_FAILED" and http_status is 422. It is not retryable — pipelines must be re-invoked explicitly with new initial_args.

PackExecutionError

Raised when cross-pack command execution fails.

from huitzo_sdk.errors import PackExecutionError

@command("workflow", namespace="automation")
async def workflow(args: Args, ctx: Context) -> dict:
    try:
        result = await ctx.execute("other-pack", "command", args={})
    except PackExecutionError as e:
        ctx.log.error(f"Cross-pack call failed: {e.pack}.{e.command}")
        ctx.log.error(f"Original error: {e.original_error}")
        raise

Attributes: - pack - Target pack namespace - command - Target command name - original_error - The underlying exception

RateLimitError

Raised when a rate limit is exceeded. The platform or external services may impose rate limits on command execution.

from huitzo_sdk.errors import RateLimitError

@command("bulk-process", namespace="data")
async def bulk_process(args: Args, ctx: Context) -> dict:
    try:
        result = await process_batch(args.items)
    except RateLimitError as e:
        ctx.log.warning(
            f"Rate limit hit. Retry after {e.retry_after}s",
            extra={"limit": e.limit, "current": e.current}
        )
        # Return partial results or schedule for later
        return {
            "status": "rate_limited",
            "retry_after": e.retry_after,
            "processed": partial_results
        }

Attributes: - retry_after - Seconds to wait before retrying (from rate limit header) - limit - The rate limit that was exceeded (e.g., "100/hour") - current - Current usage count when limit was hit

Note: The platform automatically handles RateLimitError with exponential backoff for retryable commands. See Automatic Retry Behavior below.

Automatic Retry Behavior

The SDK automatically retries commands on certain transient errors:

Retryable Errors

Error Type Retried Max Attempts Backoff
Network timeout ✅ 3 Exponential
Connection reset ✅ 3 Exponential
Rate limit (429) ✅ 5 Rate limit header
Server error (5xx) ✅ 3 Exponential
RateLimitError ✅ 5 Rate limit header
ValidationError ❌ - -
CommandError ❌ - -
PackPermissionError ❌ - -
ConfigurationError ❌ - -

Configuring Retries

@command(
    "api-call",
    namespace="external",
    retries=5,           # Max retry attempts
    retry_backoff=2.0,   # Backoff multiplier
    retry_max_wait=60,   # Max wait between retries (seconds)
)
async def api_call(args: Args, ctx: Context) -> dict:
    ...

Disabling Retries

@command("no-retry", namespace="critical", retries=0)
async def no_retry(args: Args, ctx: Context) -> dict:
    # This command will not be retried on failure
    ...

Error Response Format

When a command raises an SDK error on the platform, the caller (REST, MCP or a task poll) gets an answer decided by the SDK class, not by your exception instance. The full per-class table is Errors a command raises. In short:

  • Status, code and type come from the nearest class huitzo_sdk.errors exports. A subclass you define answers with its SDK base's values, whatever http_status, code or retryable it declares.
  • details are never returned. Put what the caller needs in message.
  • Your message reaches the caller only from a class written for the caller: ValidationError, CommandError and its subclasses, PackPermissionError, ExternalAPIError, SecretsError, RateLimitError, CommandTimeoutError, ExtensionNotAvailable, CronError and IntegrationLifecycleError. Keep it to one readable line: the platform may replace control characters with spaces and cut it to 1024 characters.
  • Every other class gets a fixed text, such as An integration call failed. for IntegrationError or The storage operation failed. for StorageError. The platform raises those families with URLs, SQL and upstream response bodies in the message, so no message of theirs is returned. That includes HuitzoError itself and a class you derive directly from it (The command failed.).
# pseudocode: the REST answer when a command raises
#   ValidationError(field="count", value=-5, message="Count must be non-negative")
HTTP 400
{
  "success": false,
  "error": {
    "message": "Count must be non-negative",
    "details": { "correlation_id": "abc-123-def" }
  }
}

# pseudocode: the REST answer when a command raises
#   ExternalAPIError(service="plaid", message="Plaid rejected the API key.")
HTTP 502
{
  "success": false,
  "error": {
    "message": "Plaid rejected the API key.",
    "type": "ExternalAPIError",
    "code": "EXTERNAL_API_ERROR",
    "details": { "correlation_id": "abc-123-def", "retryable": false }
  }
}

ValidationError, PackPermissionError and CommandError are answered with 400, 403 and 422 and carry only the message and correlation_id. The local sandbox is a development tool and answers differently: it returns your exception's own class name, code, http_status and text, so you can see exactly what your pack raised.

Error Codes

Which of these codes a caller sees, and with which status, is decided per SDK class as described above. ValidationError, PackPermissionError and CommandError are answered without a code.

Code HTTP Status Description
COMMAND_FAILED 422 General command execution failure
VALIDATION_FAILED 400 Input validation error
SECRET_MISSING 400 Required user secret not configured
PERMISSION_DENIED 403 Insufficient permissions
NOT_FOUND 404 Resource not found
TIMEOUT 504 Command timeout exceeded (CommandTimeoutError declares 408; a 408 would make clients resend the request)
RATE_LIMITED 429 Rate limit exceeded
INTERNAL_ERROR 500 Unexpected server error
EXTERNAL_API_ERROR 502 User-configured external API failure
SSH_ERROR 502 SSH connection or execution failure
INTEGRATION_ERROR 502 Platform service failure
SERVICE_UNAVAILABLE 503 Service temporarily unavailable

Logging Errors with Correlation IDs

Always use the context logger to ensure correlation IDs are included:

@command("example", namespace="demo")
async def example(args: Args, ctx: Context) -> dict:
    try:
        result = await risky_operation()
    except Exception as e:
        # ✅ Good: Uses context logger (includes correlation_id)
        ctx.log.error(
            "Operation failed",
            extra={
                "error_type": type(e).__name__,
                "error_message": str(e),
                "args": args.model_dump(),
            }
        )
        raise

    return result

Log output includes correlation ID automatically:

{
  "level": "ERROR",
  "message": "Operation failed",
  "correlation_id": "abc-123-def",
  "tenant_id": "org_456",
  "user_id": "user_789",
  "command": "demo.example",
  "error_type": "ValueError",
  "error_message": "Invalid input",
  "timestamp": "2026-01-22T10:30:00Z"
}

Best Practices

1. Be Specific with Exceptions

# ✅ Good: Specific exception with context
raise ValidationError(
    field="email",
    value=args.email,
    message="Invalid email format"
)

# ❌ Bad: Generic exception
raise Exception("Bad email")

2. Include Actionable Information

# ✅ Good: Tells user what to do
raise ValidationError(
    field="file_size",
    value=f"{size_mb}MB",
    message=f"File size ({size_mb}MB) exceeds maximum of 10MB. Please compress or split the file."
)

# ❌ Bad: No guidance
raise ValidationError(field="file_size", value=size_mb, message="Too big")

3. Clean Up on Errors

@command("process-file", namespace="files")
async def process_file(args: Args, ctx: Context) -> dict:
    temp_file = None
    try:
        temp_file = await download_file(args.url)
        result = await process(temp_file)
        return result
    except Exception:
        ctx.log.error("Processing failed, cleaning up")
        raise
    finally:
        if temp_file:
            await cleanup(temp_file)

4. Don't Swallow Errors Silently

# ✅ Good: Log and handle appropriately
try:
    result = await external_api.call()
except HTTPError as e:
    ctx.log.warning(f"API call failed: {e.status_code}")
    return {"status": "degraded", "cached": True, "data": cached_data}

# ❌ Bad: Silent failure
try:
    result = await external_api.call()
except:
    pass  # Never do this!

5. Put What the Caller Needs in the Message

The platform never returns an exception's details to a caller; they stay on the exception for your own handlers and logs. Write what failed and what to do in message, on a class whose message reaches the caller (see Error Response Format):

# pseudocode
# ✅ Good: the caller reads why it failed and what to do
raise ExternalAPIError(
    service="payment-provider",
    message="The payment provider declined the card. Try another card.",
)

# ❌ Bad: the caller is told "An integration call failed." and never sees details
raise IntegrationError(
    service="payment-provider",
    message="Payment declined",
    details={"provider_code": "CARD_DECLINED"},
)

Custom Error Types

Pack developers can subclass SDK errors to create domain-specific errors for the pack's own except clauses, logs and tests. What a caller receives is decided by the SDK class you subclass, not by your class (see Error Response Format).

Extending an SDK Error

Pick the SDK class whose answer fits, then subclass it:

Subclass The caller gets Use for
ValidationError 400 and your message Input the caller can fix
CommandError 422 and your message A failure the caller should read about
ExternalAPIError 502 and your message A failure of a third-party service the user configured
IntegrationError, HuitzoError and the other platform families A fixed text such as An integration call failed. A failure whose details the caller should not see

Your class may still declare code, http_status and retryable and add fields. Code that catches the error in-process sees them, and so does the local sandbox, but they do not change the platform's answer: status, code, type and retryable come from the nearest SDK class, and details are never returned.

# pseudocode: custom error pattern

class ClaimValidationError(ValidationError):
    # Seen in-process and by the local sandbox; a caller gets ValidationError's 400
    code = "CLAIM_VALIDATION_FAILED"
    # add domain fields, e.g. claim_id
    ...

class InsuranceAPIError(ExternalAPIError):
    # A caller gets ExternalAPIError's 502 and this error's message
    ...

Using Custom Errors

# pseudocode: raising custom errors in a command

@command("submit-claim", namespace="claims")
async def submit_claim(args, ctx):
    # Input the caller can fix: they read this message with a 400
    if not args.policy_number.startswith("POL-"):
        raise ClaimValidationError(
            field="policy_number",
            value=args.policy_number,
            message="Policy numbers start with 'POL-'.",
            claim_id=args.claim_id,
        )

    # Upstream failure: chain the original exception for your logs; the
    # caller reads only this message, never the chained cause
    try:
        result = await ctx.http.post(...)
    except HTTPError as e:
        raise InsuranceAPIError(
            provider="acme-insurance",
            endpoint="/claims",
            message="The insurer did not accept the claim. Try again later.",
        ) from e

    return result

Error Response Format

A custom error is answered as its nearest SDK class. For the two errors above:

# pseudocode: the REST answer for ClaimValidationError
HTTP 400
{
  "success": false,
  "error": {
    "message": "Policy numbers start with 'POL-'.",
    "details": { "correlation_id": "abc-123-def" }
  }
}

# pseudocode: the REST answer for InsuranceAPIError
HTTP 502
{
  "success": false,
  "error": {
    "message": "The insurer did not accept the claim. Try again later.",
    "type": "ExternalAPIError",
    "code": "EXTERNAL_API_ERROR",
    "details": { "correlation_id": "abc-123-def", "retryable": false }
  }
}

Neither your class name, your code nor fields such as claim_id appear: the platform does not serialize your class's attributes.

Custom Error Attributes

Attribute Type What it does
message str The caller's text, when the nearest SDK class is one whose message reaches the caller
code str Seen in-process and by the local sandbox. A caller gets the nearest SDK class's code
http_status int Seen in-process and by the local sandbox. A caller gets the nearest SDK class's status
retryable bool Seen in-process and by the local sandbox. A caller gets the nearest SDK class's retryable
details dict For your own handlers and logs. Never returned to a caller

Extending Integration Errors

For a service the user configured with their own credentials, extend ExternalAPIError, so the caller reads your message:

# pseudocode: a pack's own upstream error

class InsuranceAPIError(ExternalAPIError):
    """The insurance provider rejected or failed a request."""

    def __init__(self, *, provider, endpoint, message):
        super().__init__(service=f"insurance:{provider}", message=message)
        self.provider = provider
        self.endpoint = endpoint  # for your logs; never returned to a caller

Subclass IntegrationError directly only when the caller should not read the message: the platform answers such a subclass with 502 and An integration call failed..

Error Hierarchy Best Practices

  1. Subclass the SDK class whose answer fits: ValidationError, CommandError or ExternalAPIError when the caller should read your message
  2. Put what the caller needs in message: what failed and what to do; details and extra fields stay server-side
  3. Keep secrets and upstream response bodies out of message: the caller receives it as you wrote it
  4. Use code and extra fields for your own handling: they serve your except clauses, logs and tests, not the caller
ValidationError (SDK)
└── ClaimValidationError      # Input the caller can fix
CommandError (SDK)
├── ClaimProcessingError      # Processing failures
└── PolicyLookupError         # Policy not found
ExternalAPIError (SDK)
└── InsuranceAPIError         # External API failures

Testing Error Handling

import pytest
from huitzo_sdk.errors import ValidationError
from huitzo_sdk.testing import MockContext

async def test_validation_error():
    ctx = MockContext()

    with pytest.raises(ValidationError) as exc_info:
        await my_command(InvalidArgs(count=-1), ctx)

    assert exc_info.value.field == "count"
    assert "non-negative" in exc_info.value.message

async def test_error_logging():
    ctx = MockContext()

    with pytest.raises(SomeError):
        await my_command(args, ctx)

    # Verify error was logged
    assert ctx.log.error.called
    assert "correlation_id" in ctx.log.error.call_args


async def test_custom_error():
    """Test custom pack errors."""
    from my_pack.errors import ClaimValidationError

    ctx = MockContext()

    with pytest.raises(ClaimValidationError) as exc_info:
        await process_claim(InvalidClaimArgs(policy_number="INVALID"), ctx)

    error = exc_info.value
    assert error.claim_id == "CLM-12345"
    assert error.field == "policy_number"
    assert error.code == "CLAIM_VALIDATION_FAILED"