python-error-handling
Skill này làm gì
Skill này giúp bạn viết chương trình Python xử lý lỗi một cách uyển chuyển. Nó dạy cách kiểm tra dữ liệu đầu vào, dùng thông báo lỗi rõ ràng và quản lý thất bại mà không làm sập toàn bộ chương trình.
Khi nào nên dùng
- ✓Khi bạn cần kiểm tra xem dữ liệu do người dùng hoặc chương trình khác gửi có đúng không.
- ✓Khi bạn tạo thông báo lỗi giải thích vấn đề và cách khắc phục.
- ✓Khi chương trình xử lý nhiều thứ và lỗi ở một mục không nên làm dừng mọi thứ.
Liên kết skill
https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-error-handling/SKILL.mdSao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.
Cách dùng
Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.
Tin nhắn có sẵn để dán
Dành cho Claude Code, Codex hoặc Cursor: chạy lệnh trong thư mục dự án của bạn và skill sẽ được cài đặt.
Tải tệp SKILL.md về và thả vào thư mục skill của agent.
Ví dụ cách nhờ AI
“Làm sao để đảm bảo số trang người dùng yêu cầu nằm trong khoảng từ 1 đến 100?”
5 skill mới mỗi tuần. Đọc chỉ 1 phút.
Cách hoạt động
Chương trình kiểm tra thông tin nhận được ngay từ đầu. Nếu có gì sai, nó cảnh báo ngay với thông báo rõ ràng. Nếu đang xử lý nhiều mục, nó cố gắng tiếp tục ngay cả khi một mục lỗi, ghi lại mục nào thành công và mục nào thất bại.
Nội dung kỹ thuật (SKILL.md gốc)
Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.
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 |
…
Câu hỏi thường gặp
Tại sao cần kiểm tra dữ liệu sớm?
Kiểm tra dữ liệu ngay từ đầu (gọi là “fail fast”) giúp chương trình không lãng phí thời gian và tài nguyên để xử lý thông tin không hợp lệ, và dễ xác định vấn đề hơn.
“Meaningful exceptions” là gì?
Đó là các loại lỗi cụ thể (như `ValueError` hoặc `TypeError`) nói chính xác điều gì sai, vì sao và cách khắc phục, thay vì một lỗi chung chung.
Làm sao xử lý thất bại khi xử lý nhiều mục?
Thay vì dừng mọi thứ khi một mục lỗi, chương trình có thể ghi lại lỗi đó và tiếp tục xử lý các mục khác, rồi báo lại mục nào thành công và mục nào thất bại.
Chi tiết
Mô tả gốc của tác giả
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
Độ phổ biến
- Sao GitHub
- 41k
- Vị trí xếp hạng
- #6761
- Giấy phép
- MIT
- Cập nhật
- 15/10/2026
Bình luận
- …
Thêm skill từ kho mã này
screen-reader-testing
41kGiúp agent của bạn kiểm thử website bằng trình đọc màn hình để đảm bảo chúng có thể truy cập được.
wcag-audit-patterns
41kGiúp agent của bạn kiểm toán website về khả năng truy cập và sửa các vấn đề theo hướng dẫn WCAG.
multi-reviewer-patterns
41kCho phép agent của bạn điều phối các đợt rà soát mã song song, loại bỏ phát hiện trùng lặp và tổng hợp báo cáo.
parallel-debugging
41kCho phép agent gỡ lỗi các vấn đề phức tạp bằng cách điều tra song song và phân tích nguyên nhân gốc.
Skill tương tự
diffs
394kGiúp agent của bạn tạo một diff có thể chia sẻ về các chỉnh sửa, dưới dạng liên kết xem hoặc file ảnh, thay vì một bản tóm tắt viết tay.
coding-agent
394kGiúp agent của bạn giao một việc lập trình lớn cho Codex, Claude Code hoặc OpenCode chạy nền, rồi theo dõi tiến độ của nó.
gh-issues
394kGiúp agent của bạn tìm issue trên GitHub, chọn những issue cần xử lý và mở pull request với bản sửa, kể cả theo dõi nhận xét đánh giá.