All skills
wshobson avatar

/python-error-handling

@be57c0b
by Seth Hobsonwshobson/agents40k stars
4,281

Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robust APIs.

Use this Skill: https://skilld.dev/gh/wshobson/agents/python-error-handling

This session only. Nothing lands on disk.

referencesdetails.md

≈1.2k tokens on demand. Your agent reads this file only when SKILL.md points to it.

python-error-handling — detailed worked examples

Advanced Patterns

Pattern 5: Custom Exceptions with Context

Create domain-specific exceptions that carry structured information.

class ApiError(Exception):
    """Base exception for API errors."""

    def __init__(
        self,
        message: str,
        status_code: int,
        response_body: str | None = None,
    ) -> None:
        self.status_code = status_code
        self.response_body = response_body
        super().__init__(message)

class RateLimitError(ApiError):
    """Raised when rate limit is exceeded."""

    def __init__(self, retry_after: int) -> None:
        self.retry_after = retry_after
        super().__init__(
            f"Rate limit exceeded. Retry after {retry_after}s",
            status_code=429,
        )

# Usage
def handle_response(response: Response) -> dict:
    match response.status_code:
        case 200:
            return response.json()
        case 401:
            raise ApiError("Invalid credentials", 401)
        case 404:
            raise ApiError(f"Resource not found: {response.url}", 404)
        case 429:
            retry_after = int(response.headers.get("Retry-After", 60))
            raise RateLimitError(retry_after)
        case code if 400 <= code < 500:
            raise ApiError(f"Client error: {response.text}", code)
        case code if code >= 500:
            raise ApiError(f"Server error: {response.text}", code)

Pattern 6: Exception Chaining

Preserve the original exception when re-raising to maintain the debug trail.

import httpx

class ServiceError(Exception):
    """High-level service operation failed."""
    pass

def upload_file(path: str) -> str:
    """Upload file and return URL."""
    try:
        with open(path, "rb") as f:
            response = httpx.post("https://upload.example.com", files={"file": f})
            response.raise_for_status()
            return response.json()["url"]
    except FileNotFoundError as e:
        raise ServiceError(f"Upload failed: file not found at '{path}'") from e
    except httpx.HTTPStatusError as e:
        raise ServiceError(
            f"Upload failed: server returned {e.response.status_code}"
        ) from e
    except httpx.RequestError as e:
        raise ServiceError(f"Upload failed: network error") from e

Pattern 7: Batch Processing with Partial Failures

Never let one bad item abort an entire batch. Track results per item.

from dataclasses import dataclass

@dataclass
class BatchResult[T]:
    """Results from batch processing."""

    succeeded: dict[int, T]  # index -> result
    failed: dict[int, Exception]  # index -> error

    @property
    def success_count(self) -> int:
        return len(self.succeeded)

    @property
    def failure_count(self) -> int:
        return len(self.failed)

    @property
    def all_succeeded(self) -> bool:
        return len(self.failed) == 0

def process_batch(items: list[Item]) -> BatchResult[ProcessedItem]:
    """Process items, capturing individual failures.

    Args:
        items: Items to process.

    Returns:
        BatchResult with succeeded and failed items by index.
    """
    succeeded: dict[int, ProcessedItem] = {}
    failed: dict[int, Exception] = {}

    for idx, item in enumerate(items):
        try:
            result = process_single_item(item)
            succeeded[idx] = result
        except Exception as e:
            failed[idx] = e

    return BatchResult(succeeded=succeeded, failed=failed)

# Caller handles partial results
result = process_batch(items)
if not result.all_succeeded:
    logger.warning(
        f"Batch completed with {result.failure_count} failures",
        failed_indices=list(result.failed.keys()),
    )

Pattern 8: Progress Reporting for Long Operations

Provide visibility into batch progress without coupling business logic to UI.

from collections.abc import Callable

ProgressCallback = Callable[[int, int, str], None]  # current, total, status

def process_large_batch(
    items: list[Item],
    on_progress: ProgressCallback | None = None,
) -> BatchResult:
    """Process batch with optional progress reporting.

    Args:
        items: Items to process.
        on_progress: Optional callback receiving (current, total, status).
    """
    total = len(items)
    succeeded = {}
    failed = {}

    for idx, item in enumerate(items):
        if on_progress:
            on_progress(idx, total, f"Processing {item.id}")

        try:
            succeeded[idx] = process_single_item(item)
        except Exception as e:
            failed[idx] = e

    if on_progress:
        on_progress(total, total, "Complete")

    return BatchResult(succeeded=succeeded, failed=failed)

Source: SKILL.md on GitHub

No alerts17d5 checks · Risk SAFE
  • Gen Agent Trust Hub17d

    This skill is an educational resource providing best practices for Python error handling and input validation. It does not contain any malicious code, obfuscation, or unauthorized data access.

  • Socket17d

    No alerts

  • Snyk17d

    Risk: LOW · No issues

  • Runlayer7mo

    1 file scanned · No issues

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at be57c0b. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 3 days ago.

Activeupdated 4 months ago
  • Python
  • error-handling
  • validation
  • exceptions
  • input-validation
  • pydantic
  • api-design
  • batch-processing

README badge

README badge for wshobson/agents/python-error-handling

Teaches Python input validation, exception hierarchies, and partial failure handling for batch operations. Covers fail-fast patterns, Pydantic models for structured validation, and meaningful exception messages for APIs and data processing workflows.

Generated from the current SKILL.md.

Does this skill cover async error handling?
The SKILL.md focuses on synchronous patterns. It does not include async-specific error handling like asyncio exception groups or timeout patterns.
What Python versions does this skill target?
The skill uses modern Python syntax (e.g. type hints, match statements in examples) but does not explicitly state a minimum version requirement.
Does this include logging integration?
The skill mentions logging with context as a best practice but does not provide logging implementation patterns or examples.
Can I use this skill with FastAPI or Flask?
Yes. The patterns for input validation and exception hierarchies apply to any Python web framework, though the skill does not include framework-specific examples.
Does this skill require Pydantic?
No. Pydantic is optional and shown as one pattern for complex validation. The skill covers validation with plain Python exceptions as well.

Generated from the current SKILL.md. These answers refresh after source changes.