本文へスキップ
Skillpedia
一般的なプログラミング41k · #6761

python-error-handling

できること

このスキルは、エラーをうまく扱えるPythonプログラムを作るのに役立ちます。入力された情報を確認する方法、分かりやすいエラーメッセージの使い方、そして一部の失敗でプログラム全体が止まらないようにする方法を教えてくれます。

使う場面

  • ✓ユーザーや別のプログラムから送られてきたデータが正しいかを確認したいとき。
  • ✓何が問題で、どう直せばよいかを説明するエラーメッセージを作るとき。
  • ✓多くの処理を行うプログラムで、一つの項目の失敗によって全体が止まってほしくないとき。

スキルのリンク

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

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-error-handling/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“ユーザーが要求するページ数が1から100の間に収まるようにするには、どうすればよいですか?”

毎週5つの新しいスキル。1分で読めます。

仕組み

プログラムは、受け取った情報を最初の段階で確認します。問題があれば、すぐに分かりやすいメッセージで知らせてくれます。多くの項目を処理する場合は、一つが失敗しても他の処理を続けようとし、成功したものと失敗したものを記録します。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)を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

…

よくある質問

データの確認を早い段階で行うことが大切なのはなぜですか?

「早く失敗させる(fail fast)」と呼ばれるこの考え方により、不正なデータを処理して時間や資源を無駄にすることを防ぎ、問題の原因も見つけやすくなります。

「意味のある例外」とは何ですか?

`ValueError`や`TypeError`のように、何が間違っていたのか、なぜ起きたのか、どう直せばよいのかが分かる具体的なエラーの種類のことです。曖昧な一般的エラーとは違います。

多くの項目を処理するとき、失敗にはどう対応すればよいですか?

一つが失敗したら全体を止めるのではなく、その失敗を記録して他の項目の処理を続けます。そのうえで、後からどれが成功し、どれが失敗したかを報告できるようにします。

詳細

作者による元の説明

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

人気

GitHubのスター
41k
ランキング
#6761
ライセンス
MIT
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル