Claude Marketplaces
SkillsMCP serversMarketplacesDigestTools
Submit

This week in Claude

Every Monday: Claude Code, Agent SDK, MCP, and the Anthropic platform moves worth your time.

Skills by category
Frontend DevelopmentBackend & APIsTesting & QASecurityDevOps & CI/CDGit & Pull RequestsDocumentationCode Review & QualityAI & Agent BuildingSkill Development
MCP servers by category
Sales & MarketingWeb & Browser AutomationDatabasesAI & LLM ToolsCloud & InfrastructureCommunication & MessagingDeveloper ToolsDesign & CreativeDocuments & KnowledgeSearch & Web Crawling
Marketplaces by category
AI Agents & OrchestrationLLM IntegrationDevelopment ToolsFrontend & UIBackend & APIsDatabasesTesting & Code QualityDevOps & CloudSecurity & ComplianceGit & Version Control
Claude Marketplaces

An independent directory of skills, plugins and MCP servers for Claude Code. Not affiliated with Anthropic.

Browse

  • Skills
  • MCP servers
  • Marketplaces
  • Weekly digest
  • Skill index
  • MCP index
  • Marketplace index

Site

  • About
  • Tools
  • Submit
  • Feedback
  • Privacy
  • llms.txt
  • Plugins reference

Maker

  • Snug
  • Agent Caffeine
  • knobs
  • Wax
  • Vectoys
  • mertduzgun.com
Crafted at
Skills/Debugging
wshobson avatar

Python Error Handling

wshobson/agents

This covers the error handling patterns you actually need in production Python code. It shows you how to validate inputs early with clear error messages, use Pydantic for complex validation, chain exceptions to preserve debug context, and handle partial failures in batch operations without aborting everything. The custom exception hierarchy examples are solid, and the batch processing pattern that tracks successes and failures separately will save you headaches when processing large datasets. Good practical coverage of turning messy failure scenarios into manageable, debuggable code.

installs
14.2K
GitHub stars
41.8K
last updated
Aug 21, 2026
View on GitHubSave

Install

$ npx -y skills add wshobson/agents --skill python-error-handling --agent claude-code

Installs into .claude/skills of the current project.

Files

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

Sponsors

SnugThe clipboard manager you and your agent can use, safelyAgent CaffeineClose your lid, come back to finished workWaxBlock anything with supervision, without erasing your iPhoneOpen StepsSponsoredFree and open-source skills that make AI coding agents easier to understand, verify, and control.

Details

Repository
github.com/wshobson/agents
Categories
Debugging, Automation & Workflows, Python

More from wshobson/agents

All 174
  • Rag Implementation14K
  • Deployment Pipeline Design13.9K
  • Changelog Automation13.8K
  • Visual Design Foundations13.7K
  • Bash Defensive Patterns13.5K
  • Debugging Strategies13.5K
  • Stripe Integration13.5K
  • Python Anti Patterns13.4K
  • Microservices Patterns13.3K
  • Web Component Design13.3K
  • Langchain Architecture13.2K
  • Secrets Management13.2K
  • Gitlab Ci Patterns13.2K
  • Grafana Dashboards13.2K
  • Python Packaging13K
  • Llm Evaluation12.9K
  • Protocol Reverse Engineering12.8K
  • Python Type Safety12.8K
  • React Modernization12.7K
  • Startup Financial Modeling12.7K
  • Wcag Audit Patterns12.6K
  • Workflow Orchestration Patterns12.1K
  • Unity Ecs Patterns12.1K
  • Helm Chart Scaffolding12.1K

Recommended

More Debugging
1hyf0 avatarvue-debug-guideshyf0/vue-skillsComprehensive Vue 3 debugging reference covering reactivity, components, templates, lifecycle, SSR, and 100+ common runtime issues.14.2Kinstalls
2openai avatargh-fix-ciopenai/skillsUse when a user asks to debug or fix failing GitHub PR checks that run in GitHub Actions; use `gh` to inspect checks and logs, summarize failure context, draft 11.5Kinstalls
3wshobson avatarparallel-debuggingwshobson/agentsDebug complex issues using competing hypotheses with parallel investigation, evidence collection, and root cause arbitration. Use this skill when debugging bugs10.1Kinstalls
4getsentry avatarsentry-fix-issuesgetsentry/sentry-for-aiFind and fix issues from Sentry using MCP. Use when asked to fix Sentry errors, debug production issues, investigate exceptions, or resolve bugs reported in Sen10Kinstalls
5clickhouse avatarclickhouse-js-node-troubleshootingclickhouse/agent-skillsTroubleshoot and resolve common issues with the ClickHouse Node.js client (@clickhouse/client). Use this skill whenever a user reports errors, unexpected behavi7.6Kinstalls
6forcedotcom avatarplatform-apex-logs-debugforcedotcom/sf-skillsSalesforce debug log analysis and troubleshooting with 100-point scoring. TRIGGER when: user analyzes debug logs, hits governor limits, reads stack traces, or t6.8Kinstalls