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。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 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
评论
- …