Master error handling patterns across languages including

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

Error handling patterns cover

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…

---
name: error-handling-patterns
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.
---

# 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

Overview

Build resilient applications with robust error handling strategies that gracefully handle failures and provide excellent debugging experiences.

Manual install (npx, ZIP)
Claude Codenpx skills add wshobson/agents --skill error-handling-patterns -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \ | tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/developer-essentials/skills/error-handling-patterns
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/08558dc9002e5dab71f2/error-handling-patterns.zip" -OutFile "$env:TEMP\error-handling-patterns.zip"; Expand-Archive "$env:TEMP\error-handling-patterns.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md4.0 KB
  • references/1 file · 12.2 KB
Read the files here
wshobson/4236bb92 files
SKILL.md
Show the full text122 lines

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
# 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 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
1---
2name: error-handling-patterns
3description: 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 
8Build 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 
55Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.
56 
57## Best Practices
58 
591. **Fail Fast**: Validate input early, fail quickly
602. **Preserve Context**: Include stack traces, metadata, timestamps
613. **Meaningful Messages**: Explain what happened and how to fix it
624. **Log Appropriately**: Error = log, expected failure = don't spam logs
635. **Handle at Right Level**: Catch where you can meaningfully handle
646. **Clean Up Resources**: Use try-finally, context managers, defer
657. **Don't Swallow Errors**: Log or re-throw, don't silently ignore
668. **Type-Safe Errors**: Use typed errors when possible
67 
68```python
69# Good error handling example
70def 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 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
MCPExpert debugging specialist for errors, test failuresDebugger AgentCloudAI-X/claude-workflow-v2 · by CloudAI-XExpert debugging specialist for errors, test failures, crashes, segmentation faults, memory leaks, timeouts, race conditions, deadlocks, and unexpected behavior. Use PROACTIVELY when encountering any error, exception, or failing test. Performs systematic root cause analysis.★ 1.4k GitHub starsSkillEncountering any bug, test failure, or unexpected behaviorSystematic debuggingobra/superpowers · by obraUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes★ 290k GitHub starsSkillRequires running verification commands and confirming outputVerification before completionobra/superpowers · by obraUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always★ 290k GitHub starsSkillGuides systematic root-cause debuggingDebugging and error recoveryaddyosmani/agent-skills · by addyosmaniGuides systematic root-cause debugging. Use when tests fail, builds break, something that worked yesterday broke, behavior doesn't match expectations, or you encounter any unexpected error. Use when you need to figure out what broke and why — a systematic approach to finding and fixing the root cause rather than guessing.★ 98.7k GitHub starsSkillMaster systematic debugging techniques, profiling toolsDebugging strategieswshobson/agents · by wshobsonMaster systematic debugging techniques, profiling tools, and root cause analysis to efficiently track down bugs across any codebase or technology stack. Use when investigating bugs, performance issues, or unexpected behavior.★ 39.9k GitHub starsSkillCreate structured incident response runbooksIncident runbook templateswshobson/agents · by wshobsonCreate structured incident response runbooks with step-by-step procedures, escalation paths, and recovery actions. Use this skill when building a service outage runbook for a payment processing system; creating database incident procedures covering connection pool exhaustion, replication lag, and disk space alerts; onboarding new on-call engineers who need step-by-step recovery guides written for a 3 AM brain; or standardizing escalation matrices across multiple engineering teams.★ 39.9k GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars