Generated banner for Error Handling Patterns
Generated logo for Error Handling Patterns

Error Handling Patterns

Seth HobsonCommunityCreated by Seth Hobson

  • Skill
  • Guidelines
  • Software development
  • MIT
  • No issues found

From the author

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.
— the description by Seth Hobson

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach to error handling, moving beyond basic try-catch blocks to implement resilient, maintainable, and debuggable code. It covers core philosophies like choosing between exceptions and Result types, categorizing errors into recoverable and unrecoverable, and applying best practices such as failing fast and preserving error context. The documentation includes language-specific implementations for Python and TypeScript, demonstrating custom exception hierarchies, context managers, and retry mechanisms with exponential backoff.

What it does

  • Defines clear strategies for distinguishing between recoverable and unrecoverable errors.
  • Provides patterns for custom exception hierarchies to improve error categorization.
  • Demonstrates the use of context managers for reliable resource cleanup.
  • Implements retry logic with exponential backoff to handle transient failures.
  • Explains the trade-offs between using exceptions and functional Result types.
  • Offers best practices for logging, preserving stack traces, and avoiding common pitfalls.

When to use it

  • When designing error-resilient APIs or backend services.
  • During the development of new features requiring robust failure handling.
  • When refactoring code to improve reliability and debugging experiences.
  • When implementing fault-tolerant mechanisms like circuit breakers or retries.
  • When standardizing error reporting across a codebase.

Advantages

  • Reduces production downtime by handling expected failures gracefully.
  • Improves developer productivity by providing meaningful, context-rich error messages.
  • Prevents common bugs like swallowed exceptions or resource leaks.
  • Promotes consistent error handling patterns across team projects.

Usage examples

“How should I structure custom exceptions in Python for a web API?”
The skill provides a base ApplicationError class and examples of extending it for specific scenarios like ValidationError or NotFoundError, including metadata and status codes.
“Implement a retry mechanism for an external API call in Python.”
The skill provides a reusable @retry decorator that supports configurable max attempts, backoff factors, and specific exception filtering.
“What is the best way to ensure database connections are closed after an error?”
The skill demonstrates using context managers to wrap database transactions, ensuring that sessions are committed, rolled back, or closed appropriately.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/wshobson/error-handling-patterns/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip error-handling-patterns.zip -d .agents/skills

Documentation by Seth Hobson

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

Files

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Seth Hobson
Publisher
Seth Hobson (Community)
Source
wshobson/agents · plugins/developer-essentials/skills/error-handling-patterns · commit 4bde316
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Seth Hobson or Seth Hobson.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download error-handling-patterns.zip