본문으로 건너뛰기
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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

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.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 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

…

자주 묻는 질문

데이터를 일찍 확인하는 것이 왜 중요한가요?

'빨리 실패하기'라고도 하며, 잘못된 정보를 처리하느라 시간과 자원을 낭비하지 않게 하고 문제를 쉽게 찾을 수 있게 합니다.

'의미 있는 예외'란 무엇인가요?

`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

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬