Skip to content
Skillpedia
General coding41k · #4928

python-error-handling

Enables your agent to handle errors and validate data in Python. Useful for building more reliable programs that know how to react to problems.

What it does

This skill helps you build Python computer programs that handle errors gracefully. It teaches how to check input information, use clear error messages, and manage failures without crashing the entire program.

When to use it

  • ✓When you need to check if data sent by a user or another program is correct.
  • ✓When creating error messages that explain the problem and how to fix it.
  • ✓When a program processes many things, and a failure in one item shouldn't stop everything.

Example of what to ask your AI

“How can I ensure the number of pages a user requests is between 1 and 100?”

Want more? Open the sections below.

How to use

The easiest way: copy the message below and paste it into Claude, ChatGPT, Cursor or any AI. It reads the skill and follows the instructions.

Skill link

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-error-handling/SKILL.md

Ready-to-paste message

Use this skill to help me: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-error-handling/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
How it works

The program checks the information it receives right at the beginning. If something is wrong, it immediately warns you with a clear message. If it's processing many items, it tries to continue even if one item fails, keeping track of what succeeded and what failed.

Installation

Easiest way: copy the skill link and paste it into Claude, ChatGPT or Cursor asking it to follow the instructions.

In the terminal (Claude Code, Codex, Cursor), in your project folder:

npx skills add wshobson/agents --skill python-error-handling

Or download just the file:

curl -L https://raw.githubusercontent.com/wshobson/agents/main/plugins/python-development/skills/python-error-handling/SKILL.md -o SKILL.md
Technical content (original SKILL.md)

Original text by the author, straight from GitHub.

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 Type Exception Example
Invalid input ValueError Bad parameter values
Wrong type TypeError Expected string, got int
Missing item KeyError Dict key not found

…

FAQ

Why is it important to check data early on?

Checking data at the beginning (called 'fail fast') prevents the program from wasting time and resources processing invalid information, and makes it easier to identify the problem.

What are 'meaningful exceptions'?

These are specific error types (like `ValueError` or `TypeError`) that state exactly what went wrong, why it happened, and how to fix it, instead of a generic error.

How to handle failures when processing many items?

Instead of stopping everything if one item fails, the program can record that failure and continue processing other items, reporting later which ones succeeded and which ones failed.

Details

Original description by the author

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.

repo: wshobson/agents

Popularity

GitHub stars
41k
Ranking position
#4928
License
MIT
Updated
10/15/2026

Is this skill useful?

0

Sign in to vote.

Comments

  • …

More skills from this repository

Similar skills