Skills wshobson agents

error-handling-patterns

Use it when:
You're adding error handling to a feature, designing how an API reports failures, or making a service survive failing dependencies.
It does:
Explains when to throw exceptions, return Result types or crash, and which errors are recoverable, with idioms for Python, TypeScript, Rust and Go.
You get:
Code shaped by those rules; it adds no steps or files of its own.
Also covers:
Retries with exponential backoff, circuit breakers, collecting several errors at once, fallbacks, and pitfalls like empty catch blocks or logging and re-throwing.

TL;DR

A reference that spans languages. Exceptions are for unexpected conditions, Result types for expected failures such as validation errors, and crashes for bugs nothing can recover from. Network timeouts, missing files, bad input and rate limits are recoverable; running out of memory and null-pointer bugs are not. For each language it shows the native way: a custom exception hierarchy, context managers for cleanup and retry with backoff in Python; custom error classes, a Result type and async handling in TypeScript; Result and Option with the ? operator in Rust; returned and wrapped errors and custom error types in Go. Patterns for any language are a circuit breaker, error aggregation and graceful degradation through fallbacks. The rules: fail fast, keep context such as stack traces and metadata, write messages that say how to fix the problem, catch only where you can handle the error, always clean up resources, and never swallow an error silently.

Summarizes the skill at 4bde316.

npx skills add https://github.com/wshobson/agents --skill error-handling-patterns
Total Downloads
23,600 on skills.sh, Nov 9, 2026
Repo stars
42,334 wshobson/agents
First seen
Jan 20, 2026 on skills.sh
Weekly Downloads
247
-22% over the 8 weeks to Nov 9
Weekly values
Week toInstalls
Sep 21317
Sep 28349
Oct 5395
Oct 12368
Oct 19308
Oct 26302
Nov 2330
Nov 9247
Category

Test-first work, implementation from specs, git hygiene and scope control.

Everything for building software: planning, coding, debugging, design, frameworks, cloud, agents and skills.

Type

Knowledge and rules the agent applies while it works: best practices, design principles, API references.

Effect

Adds no side effects of its own. It shapes how the agent thinks, writes or reviews. Guidelines and routers are always effect:none, even when the task they support edits code.

Needs

Instructions only. Works in any agent that supports skills.

Publisher

Everyone else. Unverified vendor claims default to community.

Topics
Stack

SKILL.md

From wshobson/agents at 4bde316. Checked daily, last changed Nov 6, 2026.

Frontmatter
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
  • 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