Zum Inhalt springen
Skillpedia
Allgemeines Programmieren41k · #6761

python-error-handling

Was er macht

Dieser Skill hilft dir, Python-Programme zu bauen, die Fehler sauber behandeln. Er zeigt dir, wie du Eingaben prüfst, klare Fehlermeldungen verwendest und Fehler abfängst, ohne dass das gesamte Programm abstürzt.

Wann du ihn nutzt

  • ✓Wenn du prüfen musst, ob Daten, die ein Nutzer oder ein anderes Programm sendet, korrekt sind.
  • ✓Wenn du Fehlermeldungen erstellst, die das Problem und die Lösung erklären.
  • ✓Wenn ein Programm viele Dinge verarbeitet und ein Fehler bei einem Element nicht alles stoppen soll.

Link zum Skill

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

Kopiere ihn und füge ihn in deine KI ein (Claude, ChatGPT oder Cursor) mit der Bitte, den Anweisungen zu folgen.

So nutzt du ihn

Am einfachsten: Kopiere die Nachricht und füge sie in deine KI ein. Sie liest den Skill und folgt den Anweisungen.

Fertige Nachricht zum Einfügen

Nutze diesen Skill, um mir zu helfen: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-error-handling/SKILL.md Lies die SKILL.md unter diesem Link und folge ihren Anweisungen für meine Aufgabe.
Soll deine KI Skills wie diesen selbst finden?Installiere den kostenlosen Skillpedia-MCP: eine Zeile, und sie durchsucht vor jeder Aufgabe 15.000+ Skills.In 1 Minute installieren →

Beispielanfrage an deine KI

“Wie kann ich sicherstellen, dass die Anzahl der Seiten, die ein Nutzer anfordert, zwischen 1 und 100 liegt?”

5 neue Skills pro Woche. 1 Minute Lesezeit.

So funktioniert es

Das Programm prüft die erhaltenen Informationen direkt am Anfang. Wenn etwas nicht stimmt, warnt es dich sofort mit einer klaren Meldung. Wenn viele Elemente verarbeitet werden, versucht es weiterzumachen, auch wenn eines fehlschlägt, und hält fest, was erfolgreich war und was nicht.

Technischer Inhalt (originale SKILL.md)

Originaltext des Autors, auf Englisch, direkt von 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

…

Häufige Fragen

Warum ist es wichtig, Daten früh zu prüfen?

Wenn du Daten gleich am Anfang prüfst (als „Fail Fast“ bezeichnet), verschwendet das Programm keine Zeit und Ressourcen mit ungültigen Informationen, und das Problem lässt sich leichter finden.

Was sind „aussagekräftige Exceptions“?

Das sind spezifische Fehlertypen wie `ValueError` oder `TypeError`, die genau benennen, was schiefgelaufen ist, warum und wie man es beheben kann. Ein allgemeiner Fehler sagt dagegen wenig.

Wie gehe ich mit Fehlern um, wenn ich viele Elemente verarbeite?

Statt alles zu stoppen, wenn ein Element fehlschlägt, kann das Programm den Fehler festhalten und die übrigen Elemente weiterverarbeiten. Am Ende wird dann angezeigt, welche erfolgreich waren und welche nicht.

Details

Originalbeschreibung des Autors

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

Beliebtheit

GitHub-Sterne
41k
Platz im Ranking
#6761
Lizenz
MIT
Aktualisiert
15.10.2026

Ist dieser Skill nützlich?

0

Anmelden um abzustimmen.

Kommentare

  • …

Weitere Skills aus diesem Repository

Ähnliche Skills