error-handling-patterns – skill Lập trình cho agent AI
Thành thạo các mẫu xử lý lỗi trên nhiều ngôn ngữ, bao gồm exception, kiểu Result, lan truyền lỗi và suy giảm có kiểm soát, để xây dựng ứng dụng bền bỉ. Dùng khi triển khai xử lý lỗi, thiết kế API, hoặc cải thiện độ tin cậy của ứng dụng.
Cài skill error-handling-patterns bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/error-handling-patterns-40a08.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /error-handling-patterns – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/error-handling-patterns-40a08.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $error-handling-patterns – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/error-handling-patterns-40a08.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /error-handling-patterns – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/error-handling-patterns-40a08.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /error-handling-patterns – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
Error Handling Patterns
Build resilient applications with robust error handling strategies that gracefully handle failures and provide excellent debugging experiences.
When to Use This Skill
- Implementing error handling in new features
- Designing error-resilient APIs
- Debugging production issues
- Improving application reliability
- Creating better error messages for users and developers
- Implementing retry and circuit breaker patterns
- Handling async/concurrent errors
- Building fault-tolerant distributed systems
Core Concepts
1. Error Handling Philosophies
Exceptions vs Result Types:
- Exceptions: Traditional try-catch, disrupts control flow
- Result Types: Explicit success/failure, functional approach
- Error Codes: C-style, requires discipline
- Option/Maybe Types: For nullable values
When to Use Each:
- Exceptions: Unexpected errors, exceptional conditions
- Result Types: Expected errors, validation failures
- Panics/Crashes: Unrecoverable errors, programming bugs
2. Error Categories
Recoverable Errors:
- Network timeouts
- Missing files
- Invalid user input
- API rate limits
Unrecoverable Errors:
- Out of memory
- Stack overflow
- Programming bugs (null pointer, etc.)
Detailed patterns and worked examples
Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.
Best Practices
1. Fail Fast: Validate input early, fail quickly
2. Preserve Context: Include stack traces, metadata, timestamps
3. Meaningful Messages: Explain what happened and how to fix it
4. Log Appropriately: Error = log, expected failure = don't spam logs
5. Handle at Right Level: Catch where you can meaningfully handle
6. Clean Up Resources: Use try-finally, context managers, defer
7. Don't Swallow Errors: Log or re-throw, don't silently ignore
8. Type-Safe Errors: Use typed errors when possible
# Good error handling example
def process_order(order_id: str) -> Order:
"""Process order with comprehensive error handling."""
try:
# Validate input
if not order_id:
raise ValidationError("Order ID is required")
# Fetch order
order = db.get_order(order_id)
if not order:
raise NotFoundError("Order", order_id)
# Process payment
try:
payment_result = payment_service.charge(order.total)
except PaymentServiceError as e:
# Log and wrap external service error
logger.error(f"Payment failed for order {order_id}: {e}")
raise ExternalServiceError(
f"Payment processing failed",
service="payment_service",
details={"order_id": order_id, "amount": order.total}
) from e
# Update order
order.status = "completed"
order.payment_id = payment_result.id
db.save(order)
return order
except ApplicationError:
# Re-raise known application errors
raise
except Exception as e:
# Log unexpected errors
logger.exception(f"Unexpected error processing order {order_id}")
raise ApplicationError(
"Order processing failed",
code="INTERNAL_ERROR"
) from eCommon Pitfalls
- Catching Too Broadly:
except Exceptionhides bugs - Empty Catch Blocks: Silently swallowing errors
- Logging and Re-throwing: Creates duplicate log entries
- Not Cleaning Up: Forgetting to close files, connections
- Poor Error Messages: "Error occurred" is not helpful
- Returning Error Codes: Use exceptions or Result types
- Ignoring Async Errors: Unhandled promise rejections
Skill liên quan
- cfo-review – /c-level-agents:cfo-review [plan] — Rà soát hoài nghi, thiên về số liệu cho mọi kế hoạch…
- test-driven-development – Phát triển theo hướng kiểm thử bằng vòng lặp red-green-refactor. Dùng khi triển khai bất…
- app-store-changelog – Tạo ghi chú phát hành App Store hướng đến người dùng từ lịch sử git kể từ tag gần nhất.
- appium-skill – Tạo script tự động hóa ứng dụng di động Appium cấp production cho Android và iOS bằng…
- changelog-generator – Tạo ghi chú phát hành nhất quán, có thể kiểm toán từ Conventional Commits. Tách riêng…
- applicationinsights-web-ts – Gắn đo lường (instrument) cho ứng dụng web/trình duyệt bằng SDK JavaScript của…
- architect-review – Kiến trúc sư phần mềm chuyên gia, am hiểu kiến trúc hiện đại
- architecture – Khung ra quyết định kiến trúc. Phân tích yêu cầu, đánh giá trade-off, tài liệu hóa ADR…