error-handling-patterns
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.
What this skill does
# 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
### Error Handling Philosophies
| Approach | When to Use |
|----------|-------------|
| **Exceptions** (try-catch) | Unexpected errors, exceptional conditions |
| **Result Types** (Ok/Err) | Expected errors, validation failures |
| **Error Codes** | C-style APIs requiring discipline |
| **Option/Maybe Types** | Nullable values, absent data |
| **Panics/Crashes** | Unrecoverable errors, programming bugs |
### Error Categories
**Recoverable:** Network timeouts, missing files, invalid user input, API rate limits -- retry, degrade, or prompt the user.
**Unrecoverable:** Out of memory, stack overflow, null-pointer bugs -- fail fast, log, and crash cleanly.
## Universal Patterns
### Pattern 1: Circuit Breaker
Prevent cascading failures by tracking consecutive errors and short-circuiting calls to a failing dependency.
- **CLOSED** -- normal operation; failures increment a counter.
- **OPEN** -- failure threshold reached; all calls rejected immediately.
- **HALF-OPEN** -- after a timeout, allow a probe call; if it succeeds, reset to CLOSED.
```typescript
class CircuitBreaker {
private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED'
private failures = 0
private lastFailure = 0
constructor(
private threshold = 5,
private timeoutMs = 60_000,
private successesToReset = 2
) {}
async call<T>(fn: () => Promise<T>): Promise<T> {
if (this.state === 'OPEN') {
if (Date.now() - this.lastFailure > this.timeoutMs) {
this.state = 'HALF_OPEN'
} else {
throw new Error('Circuit breaker is OPEN')
}
}
try {
const result = await fn()
this.onSuccess()
return result
} catch (e) {
this.onFailure()
throw e
}
}
private onSuccess() {
this.failures = 0
if (this.state === 'HALF_OPEN') this.state = 'CLOSED'
}
private onFailure() {
this.failures++
this.lastFailure = Date.now()
if (this.failures >= this.threshold) this.state = 'OPEN'
}
}
// Usage
const breaker = new CircuitBreaker()
const data = await breaker.call(() => externalApi.getData())
```
### Pattern 2: Error Aggregation
Collect multiple errors instead of failing on the first one -- essential for form validation and batch processing.
```typescript
class ErrorCollector {
private errors: Error[] = []
add(error: Error): void { this.errors.push(error) }
hasErrors(): boolean { return this.errors.length > 0 }
throw(): never {
if (this.errors.length === 1) throw this.errors[0]
throw new AggregateError(this.errors, `${this.errors.length} errors occurred`)
}
}
// Usage: validate multiple fields at once
function validateUser(data: any): User {
const errors = new ErrorCollector()
if (!data.email) errors.add(new ValidationError('Email is required'))
else if (!isValidEmail(data.email)) errors.add(new ValidationError('Email is invalid'))
if (!data.name || data.name.length < 2)
errors.add(new ValidationError('Name must be at least 2 characters'))
if (errors.hasErrors()) errors.throw()
return data as User
}
```
### Pattern 3: Graceful Degradation
Provide fallback functionality when the primary path errors.
```python
from typing import Optional, Callable, TypeVar
T = TypeVar('T')
def with_fallback(
primary: Callable[[], T],
fallback: Callable[[], T],
log_error: bool = True
) -> T:
"""Try primary function, fall back on error."""
try:
return primary()
except Exception as e:
if log_error:
logger.error(f"Primary function failed: {e}")
return fallback()
# Usage
profile = with_fallback(
primary=lambda: fetch_from_cache(user_id),
fallback=lambda: fetch_from_database(user_id)
)
```
## 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
## 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 instead
- **Ignoring Async Errors** -- unhandled promise rejections
## Reference Files
| File | Contents |
|------|----------|
| [references/language-patterns.md](references/language-patterns.md) | Python, TypeScript, Rust, and Go error-handling idioms with full examples |
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.