{"id":"error-handling-patterns","name":"error-handling-patterns","summary":"例外、結果型、エラー伝播、優雅な劣化など、言語を超えたエラー処理パターンをマスターし、レジリエントなアプリケーションを構築しましょう。","body":"# Error Handling Patterns\n\nBuild resilient applications with robust error handling strategies that gracefully handle failures and provide excellent debugging experiences.\n\n## When to Use This Skill\n\n- Implementing error handling in new features\n- Designing error-resilient APIs\n- Debugging production issues\n- Improving application reliability\n- Creating better error messages for users and developers\n- Implementing retry and circuit breaker patterns\n- Handling async/concurrent errors\n- Building fault-tolerant distributed systems\n\n## Core Concepts\n\n### 1. Error Handling Philosophies\n\n**Exceptions vs Result Types:**\n\n- **Exceptions**: Traditional try-catch, disrupts control flow\n- **Result Types**: Explicit success/failure, functional approach\n- **Error Codes**: C-style, requires discipline\n- **Option/Maybe Types**: For nullable values\n\n**When to Use Each:**\n\n- Exceptions: Unexpected errors, exceptional conditions\n- Result Types: Expected errors, validation failures\n- Panics/Crashes: Unrecoverable errors, programming bugs\n\n### 2. Error Categories\n\n**Recoverable Errors:**\n\n- Network timeouts\n- Missing files\n- Invalid user input\n- API rate limits\n\n**Unrecoverable Errors:**\n\n- Out of memory\n- Stack overflow\n- Programming bugs (null pointer, etc.)\n\n## Detailed patterns and worked examples\n\nDetailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.\n\n## Best Practices\n\n1. **Fail Fast**: Validate input early, fail quickly\n2. **Preserve Context**: Include stack traces, metadata, timestamps\n3. **Meaningful Messages**: Explain what happened and how to fix it\n4. **Log Appropriately**: Error = log, expected failure = don't spam logs\n5. **Handle at Right Level**: Catch where you can meaningfully handle\n6. **Clean Up Resources**: Use try-finally, context managers, defer\n7. **Don't Swallow Errors**: Log or re-throw, don't silently ignore\n8. **Type-Safe Errors**: Use typed errors when possible\n\n```python\n# Good error handling example\ndef process_order(order_id: str) -> Order:\n    \"\"\"Process order with comprehensive error handling.\"\"\"\n    try:\n        # Validate input\n        if not order_id:\n            raise ValidationError(\"Order ID is required\")\n\n        # Fetch order\n        order = db.get_order(order_id)\n        if not order:\n            raise NotFoundError(\"Order\", order_id)\n\n        # Process payment\n        try:\n            payment_result = payment_service.charge(order.total)\n        except PaymentServiceError as e:\n            # Log and wrap external service error\n            logger.error(f\"Payment failed for order {order_id}: {e}\")\n            raise ExternalServiceError(\n                f\"Payment processing failed\",\n                service=\"payment_service\",\n                details={\"order_id\": order_id, \"amount\": order.total}\n            ) from e\n\n        # Update order\n        order.status = \"completed\"\n        order.payment_id = payment_result.id\n        db.save(order)\n\n        return order\n\n    except ApplicationError:\n        # Re-raise known application errors\n        raise\n    except Exception as e:\n        # Log unexpected errors\n        logger.exception(f\"Unexpected error processing order {order_id}\")\n        raise ApplicationError(\n            \"Order processing failed\",\n            code=\"INTERNAL_ERROR\"\n        ) from e\n```\n\n## Common Pitfalls\n\n- **Catching Too Broadly**: `except Exception` hides bugs\n- **Empty Catch Blocks**: Silently swallowing errors\n- **Logging and Re-throwing**: Creates duplicate log entries\n- **Not Cleaning Up**: Forgetting to close files, connections\n- **Poor Error Messages**: \"Error occurred\" is not helpful\n- **Returning Error Codes**: Use exceptions or Result types\n- **Ignoring Async Errors**: Unhandled promise rejections","author":"@wshobson","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/wshobson/agents/tree/main/plugins/developer-essentials/skills/error-handling-patterns","license":"MIT","category":null,"lang":"en","tokens":809,"stars":0,"calls30d":3,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"references/details.md","size":12510,"sha256":"6f6a48bdee3b8fccf5b73725e798725970826a53c0bb2d4cc2a8e19b1e69466f"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":[]}}