1
---
2
name: error-handling-patterns
3
description: 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.
4
---
5
6
# Error Handling Patterns
7
8
Build resilient applications with robust error handling strategies that gracefully handle failures and provide excellent debugging experiences.
9
10
## When to Use This Skill
11
12
- Implementing error handling in new features
13
- Designing error-resilient APIs
14
- Debugging production issues
15
- Improving application reliability
16
- Creating better error messages for users and developers
17
- Implementing retry and circuit breaker patterns
18
- Handling async/concurrent errors
19
- Building fault-tolerant distributed systems
20
21
## Core Concepts
22
23
### 1. Error Handling Philosophies
24
25
**Exceptions vs Result Types:**
26
27
- **Exceptions**: Traditional try-catch, disrupts control flow
28
- **Result Types**: Explicit success/failure, functional approach
29
- **Error Codes**: C-style, requires discipline
30
- **Option/Maybe Types**: For nullable values
31
32
**When to Use Each:**
33
34
- Exceptions: Unexpected errors, exceptional conditions
35
- Result Types: Expected errors, validation failures
36
- Panics/Crashes: Unrecoverable errors, programming bugs
37
38
### 2. Error Categories
39
40
**Recoverable Errors:**
41
42
- Network timeouts
43
- Missing files
44
- Invalid user input
45
- API rate limits
46
47
**Unrecoverable Errors:**
48
49
- Out of memory
50
- Stack overflow
51
- Programming bugs (null pointer, etc.)
52
53
## Detailed patterns and worked examples
54
55
Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.
56
57
## Best Practices
58
59
1. **Fail Fast**: Validate input early, fail quickly
60
2. **Preserve Context**: Include stack traces, metadata, timestamps
61
3. **Meaningful Messages**: Explain what happened and how to fix it
62
4. **Log Appropriately**: Error = log, expected failure = don't spam logs
63
5. **Handle at Right Level**: Catch where you can meaningfully handle
64
6. **Clean Up Resources**: Use try-finally, context managers, defer
65
7. **Don't Swallow Errors**: Log or re-throw, don't silently ignore
66
8. **Type-Safe Errors**: Use typed errors when possible
67
68
```python
69
# Good error handling example
70
def process_order(order_id: str) -> Order:
71
"""Process order with comprehensive error handling."""
72
try:
73
# Validate input
74
if not order_id:
75
raise ValidationError("Order ID is required")
76
77
# Fetch order
78
order = db.get_order(order_id)
79
if not order:
80
raise NotFoundError("Order", order_id)
81
82
# Process payment
83
try:
84
payment_result = payment_service.charge(order.total)
85
except PaymentServiceError as e:
86
# Log and wrap external service error
87
logger.error(f"Payment failed for order {order_id}: {e}")
88
raise ExternalServiceError(
89
f"Payment processing failed",
90
service="payment_service",
91
details={"order_id": order_id, "amount": order.total}
92
) from e
93
94
# Update order
95
order.status = "completed"
96
order.payment_id = payment_result.id
97
db.save(order)
98
99
return order
100
101
except ApplicationError:
102
# Re-raise known application errors
103
raise
104
except Exception as e:
105
# Log unexpected errors
106
logger.exception(f"Unexpected error processing order {order_id}")
107
raise ApplicationError(
108
"Order processing failed",
109
code="INTERNAL_ERROR"
110
) from e
111
```
112
113
## Common Pitfalls
114
115
- **Catching Too Broadly**: `except Exception` hides bugs
116
- **Empty Catch Blocks**: Silently swallowing errors
117
- **Logging and Re-throwing**: Creates duplicate log entries
118
- **Not Cleaning Up**: Forgetting to close files, connections
119
- **Poor Error Messages**: "Error occurred" is not helpful
120
- **Returning Error Codes**: Use exceptions or Result types
121
- **Ignoring Async Errors**: Unhandled promise rejections
122