Saltar al contenido
Skillpedia
Programación general41 mil · #6761

python-error-handling

Qué hace

Esta skill te ayuda a crear programas de Python que gestionen los errores con elegancia. Te enseña a comprobar los datos de entrada, a usar mensajes de error claros y a manejar los fallos sin que se caiga todo el programa.

Cuándo usarla

  • ✓Cuando necesitas comprobar si los datos que envía un usuario o otro programa son correctos.
  • ✓Cuando quieres crear mensajes de error que expliquen el problema y cómo solucionarlo.
  • ✓Cuando un programa procesa muchos elementos y un fallo en uno de ellos no debería detener todo lo demás.

Link de la skill

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

Cópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.

Cómo usar

La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.

Mensaje listo para pegar

Usa esta skill para ayudarme: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-error-handling/SKILL.md Lee el archivo SKILL.md de ese link y sigue sus instrucciones en mi tarea.
¿Quieres que tu IA encuentre skills como esta por sí sola?Instala el MCP gratis de Skillpedia: una línea, y busca entre 15.000+ skills antes de cada tarea.Instalar en 1 minuto →

Ejemplo de qué pedirle a la IA

“¿Cómo puedo asegurarme de que el número de páginas que pide un usuario esté entre 1 y 100?”

5 skills nuevas por semana. 1 minuto de lectura.

Cómo funciona

El programa comprueba la información que recibe justo al principio. Si algo está mal, te avisa de inmediato con un mensaje claro. Si está procesando muchos elementos, intenta seguir aunque uno falle, y lleva un registro de cuáles salieron bien y cuáles fallaron.

Contenido técnico (SKILL.md original)

Texto original del autor, en inglés, directo de 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

…

Preguntas frecuentes

¿Por qué es importante comprobar los datos desde el principio?

Comprobar los datos al inicio (lo que se llama "fallar rápido") evita que el programa gaste tiempo y recursos procesando información no válida, y facilita identificar el problema.

¿Qué son las "excepciones significativas"?

Son tipos de error específicos (como `ValueError` o `TypeError`) que indican exactamente qué salió mal, por qué ocurrió y cómo corregirlo, en lugar de un error genérico.

¿Cómo manejo los fallos al procesar muchos elementos?

En lugar de detener todo si un elemento falla, el programa puede registrar ese fallo y seguir procesando los demás, e informar después cuáles salieron bien y cuáles no.

Detalles

Descripción original del autor

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

Popularidad

Estrellas en GitHub
41 mil
Posición en el ranking
#6761
Licencia
MIT
Actualizada
15/10/2026

¿Te sirve esta skill?

0

Entra para votar.

Comentarios

  • …

Más skills de este repositorio

Skills parecidas