error-handling-patterns
它能做什么
这个工具教你如何处理计算机程序中的错误。它能帮你写出更可靠的应用,让它们不容易“崩掉”,并且在出问题时给出有用的提示信息。
适用场景
- ✓当你在构建程序的新部分时。
- ✓当你希望网站或应用即使遇到问题也能继续运行时。
- ✓当你想理解并修复程序中出现的错误时。
技能链接
https://github.com/wshobson/agents/blob/main/plugins/developer-essentials/skills/error-handling-patterns/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“我怎样让我的应用在数据缺失时明确地告诉用户?”
每周 5 个新技能,1 分钟读完。
工作原理
它讲解了几种处理错误的方式,比如“异常”(exceptions,即错误警告)和“结果类型”(result types,表示成功或失败)。它还会演示如何记录错误日志,方便之后排查问题。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
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
- Fail Fast: Validate input early, fail quickly
- Preserve Context: Include stack traces, metadata, timestamps
- Meaningful Messages: Explain what happened and how to fix it
- Log Appropriately: Error = log, expected failure = don't spam logs
- Handle at Right Level: Catch where you can meaningfully handle
- Clean Up Resources: Use try-finally, context managers, defer
- Don't Swallow Errors: Log or re-throw, don't silently ignore
- 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 e
Common 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
常见问题
“异常”和“结果类型”有什么区别?
异常就像警告,会打断正常的执行流程,以便处理问题。结果类型则是一种更直接的方式,说明某个操作是成功还是失败,而且不会中断整个程序。
什么是“可恢复”和“不可恢复”的错误?
可恢复的错误是程序可以尝试修复的,比如网络临时出了问题。不可恢复的错误则很严重,比如内存耗尽,通常会导致程序停止运行。
为什么把错误“吞掉”是不好的?
忽略错误(也就是把它吞掉)会让问题一直隐藏起来,之后可能引发更大的故障。更好的做法是把错误记录下来,或者至少报告它发生过。
详情
作者的原始描述
Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.
repo: wshobson/agents
热度
- GitHub 星标
- 41k
- 排名
- #6679
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …