Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
wshobson avatar

Python Error Handling

  • 10.4k installs
  • 38.3k repo stars
  • Updated July 22, 2026
  • wshobson/agents

How to implement fail-fast input validation, design meaningful exception hierarchies, handle partial failures in batch operations, and preserve error context for debugging in Python applications.

About

Python error handling patterns for building robust applications through early input validation, meaningful exception design, and graceful failure recovery. Developers use this skill when validating API parameters, designing exception strategies for applications, handling batch operation failures, and converting external data to domain types. Key workflows include fail-fast validation before expensive operations, mapping errors to appropriate exception types, using Pydantic for structured input validation, chaining exceptions to preserve debug context, and tracking successes and failures separately in batch processing.

  • Early input validation at API boundaries before any processing begins
  • Domain type conversion using enums and Pydantic models to enforce type safety
  • Partial failure handling in batch operations that continues processing after individual item errors
  • Meaningful exception messages that explain what failed, why, and how to fix it
  • Exception chaining with 'raise ... from e' to preserve full error trail for debugging

Python Error Handling by the numbers

  • 10,385 all-time installs (skills.sh)
  • +279 installs in the week ending Jul 28, 2026 (Skillselion tracking)
  • Ranked #81 of 4,386 Backend & APIs skills by installs in the Skillselion catalog
  • Security screen: LOW risk (skills.sh audit)
  • Data as of Jul 28, 2026 (Skillselion catalog sync)
At a glance

python-error-handling capabilities & compatibility

Capabilities
input validation · exception design · batch failure handling · type conversion · error messaging
Use cases
api development · debugging · testing
Platforms
macOS · Windows · Linux
Runs
Runs locally
From the docs

What python-error-handling says it does

Validate inputs early, before expensive operations. Report all validation errors at once when possible.
Core Concepts - Fail Fast
In batch operations, don't let one failure abort everything. Track successes and failures separately.
Core Concepts - Partial Failures
Use appropriate exception types with context. Messages should explain what failed, why, and how to fix it.
Core Concepts - Meaningful Exceptions
npx skills add https://github.com/wshobson/agents --skill python-error-handling

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs10.4k
repo stars38.3k
Security audit3 / 3 scanners passed
Last updatedJuly 22, 2026
Repositorywshobson/agents

What it does

Implement input validation, exception hierarchies, and partial failure handling in Python APIs and batch processing systems.

Who is it for?

Building reliable APIs, implementing batch processing systems, designing validation logic, converting external data formats, creating user-friendly error messages.

Skip if: Frontend UI error display, real-time streaming protocols, non-blocking async error recovery patterns.

When should I use this skill?

Implementing validation logic, designing exception strategies, handling batch processing failures, building robust APIs, converting strings to domain types.

What you get

Developers can validate inputs early, use specific exception types with helpful messages, convert external data to typed domain objects, and gracefully handle failures in batch processing.

  • Input validation patterns
  • Exception hierarchy design
  • Partial failure handling code

By the numbers

  • 4 fundamental patterns documented with code examples
  • 10 best practices for error handling in Python
  • 7 standard exception types mapped to failure types

Files

SKILL.mdMarkdownGitHub ↗

Python Error Handling

Build robust Python applications with proper input validation, meaningful exceptions, and graceful failure handling. Good error handling makes debugging easier and systems more reliable.

When to Use This Skill

  • Validating user input and API parameters
  • Designing exception hierarchies for applications
  • Handling partial failures in batch operations
  • Converting external data to domain types
  • Building user-friendly error messages
  • Implementing fail-fast validation patterns

Core Concepts

1. Fail Fast

Validate inputs early, before expensive operations. Report all validation errors at once when possible.

2. Meaningful Exceptions

Use appropriate exception types with context. Messages should explain what failed, why, and how to fix it.

3. Partial Failures

In batch operations, don't let one failure abort everything. Track successes and failures separately.

4. Preserve Context

Chain exceptions to maintain the full error trail for debugging.

Quick Start

def fetch_page(url: str, page_size: int) -> Page:
    if not url:
        raise ValueError("'url' is required")
    if not 1 <= page_size <= 100:
        raise ValueError(f"'page_size' must be 1-100, got {page_size}")
    # Now safe to proceed...

Fundamental Patterns

Pattern 1: Early Input Validation

Validate all inputs at API boundaries before any processing begins.

def process_order(
    order_id: str,
    quantity: int,
    discount_percent: float,
) -> OrderResult:
    """Process an order with validation."""
    # Validate required fields
    if not order_id:
        raise ValueError("'order_id' is required")

    # Validate ranges
    if quantity <= 0:
        raise ValueError(f"'quantity' must be positive, got {quantity}")

    if not 0 <= discount_percent <= 100:
        raise ValueError(
            f"'discount_percent' must be 0-100, got {discount_percent}"
        )

    # Validation passed, proceed with processing
    return _process_validated_order(order_id, quantity, discount_percent)

Pattern 2: Convert to Domain Types Early

Parse strings and external data into typed domain objects at system boundaries.

from enum import Enum

class OutputFormat(Enum):
    JSON = "json"
    CSV = "csv"
    PARQUET = "parquet"

def parse_output_format(value: str) -> OutputFormat:
    """Parse string to OutputFormat enum.

    Args:
        value: Format string from user input.

    Returns:
        Validated OutputFormat enum member.

    Raises:
        ValueError: If format is not recognized.
    """
    try:
        return OutputFormat(value.lower())
    except ValueError:
        valid_formats = [f.value for f in OutputFormat]
        raise ValueError(
            f"Invalid format '{value}'. "
            f"Valid options: {', '.join(valid_formats)}"
        )

# Usage at API boundary
def export_data(data: list[dict], format_str: str) -> bytes:
    output_format = parse_output_format(format_str)  # Fail fast
    # Rest of function uses typed OutputFormat
    ...

Pattern 3: Pydantic for Complex Validation

Use Pydantic models for structured input validation with automatic error messages.

from pydantic import BaseModel, Field, field_validator

class CreateUserInput(BaseModel):
    """Input model for user creation."""

    email: str = Field(..., min_length=5, max_length=255)
    name: str = Field(..., min_length=1, max_length=100)
    age: int = Field(ge=0, le=150)

    @field_validator("email")
    @classmethod
    def validate_email_format(cls, v: str) -> str:
        if "@" not in v or "." not in v.split("@")[-1]:
            raise ValueError("Invalid email format")
        return v.lower()

    @field_validator("name")
    @classmethod
    def normalize_name(cls, v: str) -> str:
        return v.strip().title()

# Usage
try:
    user_input = CreateUserInput(
        email="user@example.com",
        name="john doe",
        age=25,
    )
except ValidationError as e:
    # Pydantic provides detailed error information
    print(e.errors())

Pattern 4: Map Errors to Standard Exceptions

Use Python's built-in exception types appropriately, adding context as needed.

Failure TypeExceptionExample
Invalid inputValueErrorBad parameter values
Wrong typeTypeErrorExpected string, got int
Missing itemKeyErrorDict key not found
Operational failureRuntimeErrorService unavailable
TimeoutTimeoutErrorOperation took too long
File not foundFileNotFoundErrorPath doesn't exist
Permission deniedPermissionErrorAccess forbidden
# Good: Specific exception with context
raise ValueError(f"'page_size' must be 1-100, got {page_size}")

# Avoid: Generic exception, no context
raise Exception("Invalid parameter")

Detailed worked examples and patterns

Detailed sections (starting with ## Advanced Patterns) live in references/details.md. Read that file when the navigation summary above is insufficient.

Best Practices Summary

1. Validate early - Check inputs before expensive operations 2. Use specific exceptions - ValueError, TypeError, not generic Exception 3. Include context - Messages should explain what, why, and how to fix 4. Convert types at boundaries - Parse strings to enums/domain types early 5. Chain exceptions - Use raise ... from e to preserve debug info 6. Handle partial failures - Don't abort batches on single item errors 7. Use Pydantic - For complex input validation with structured errors 8. Document failure modes - Docstrings should list possible exceptions 9. Log with context - Include IDs, counts, and other debugging info 10. Test error paths - Verify exceptions are raised correctly

Related skills

FAQ

Should I validate all inputs before any processing?

Yes - fail-fast validation at API boundaries before expensive operations makes debugging easier and prevents cascading failures.

What exception should I raise for invalid parameter values?

Use ValueError for invalid values, TypeError for wrong types, and map other failures to specific built-in exceptions like KeyError, FileNotFoundError, or TimeoutError with context in the message.

How do I handle errors in batch operations?

Track successes and failures separately instead of aborting on first error. Process all items and collect results, then report which items succeeded and which failed.

Is Python Error Handling safe to install?

skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.

Backend & APIsbackendtesting

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.