Error Handling Patterns

作者 wshobson46891e7e60da无许可证收录于 2026年10月8日更新于 2026年10月8日

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.

AI 生成的概览

跨语言错误处理模式指南,涵盖异常、Result 类型、错误传播与优雅降级。

功能
该技能提供关于软件错误处理设计与实现的指导。它讲解异常与 Result 类型等不同理念,区分可恢复与不可恢复错误,并列出最佳实践与常见陷阱。配套参考文件包含更详细的模式文档与示例,供代理在主指南不足时查阅。它产出的是建议与代码示例,而非运行工具或生成文件。
适用场景
适用于为新功能添加错误处理、设计具备容错能力的 API,或排查生产环境故障。也适合处理重试、熔断、异步错误处理与容错分布式系统,以及改进面向用户和开发者的错误信息。
运行要求
无需脚本或运行时依赖,仅包含说明文档与一份参考文件。代理可阅读 references/details.md 获取更详细的模式。

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
python
# Good error handling exampledef 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 Exception hides 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

来源与署名

来源:wshobson/agents位于plugins/developer-essentials/skills/error-handling-patterns提交46891e7

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架