error-handling-patterns
wshobson/agents
Master error handling patterns across languages to build resilient, fault-tolerant applications.
What is error-handling-patterns?
This skill teaches error handling strategies including exceptions, Result types, error propagation, and graceful degradation. Use it when implementing error handling, designing APIs, debugging production issues, or improving application reliability.
- Distinguish between exceptions, Result types, error codes, and Option/Maybe types
- Categorize errors as recoverable (timeouts, missing files, invalid input) or unrecoverable (out of memory, stack overflow)
- Implement fail-fast validation and preserve error context with stack traces and metadata
- Design meaningful error messages that explain what happened and how to fix it
- Handle async/concurrent errors and implement retry and circuit breaker patterns
- Clean up resources properly using try-finally, context managers, and defer patterns
How to install error-handling-patterns
npx skills add https://github.com/wshobson/agents --skill error-handling-patternsHow to use error-handling-patterns
- 1.Identify whether your error is recoverable (network timeout, missing file, invalid input) or unrecoverable (out of memory, programming bug)
- 2.Choose the appropriate error handling approach: exceptions for unexpected errors, Result types for expected failures, panics for unrecoverable errors
- 3.Validate input early and fail fast before attempting expensive operations
- 4.Preserve error context by including stack traces, metadata, timestamps, and relevant details
- 5.Write meaningful error messages that explain what happened, why it happened, and how to fix it
- 6.Handle errors at the appropriate level where you can meaningfully recover or provide context
- 7.Clean up resources using try-finally blocks, context managers, or defer statements
- 8.Log errors appropriately: log actual errors, but don't spam logs for expected failures
Use cases
- Implementing error handling in new features with proper validation and recovery strategies
- Designing error-resilient APIs that provide clear error messages and appropriate HTTP status codes
- Debugging production issues by preserving context, stack traces, and metadata in error logs
- Improving application reliability by categorizing errors and handling them at the appropriate level
- Building fault-tolerant distributed systems with retry logic and circuit breaker patterns
- Backend engineers implementing error handling in new features
- API designers creating robust error contracts
- DevOps and SRE teams debugging production issues
- Full-stack developers improving application reliability
- Architects designing fault-tolerant distributed systems
error-handling-patterns FAQ
Use exceptions for unexpected errors and exceptional conditions that disrupt normal flow. Use Result types for expected errors like validation failures or API errors where you want explicit success/failure handling. Result types are more functional and make error handling explicit in the type system.
Recoverable errors (network timeouts, missing files, invalid input, rate limits) can be handled with retry logic or graceful degradation. Unrecoverable errors (out of memory, stack overflow, programming bugs) should crash or panic because continuing would be unsafe.
Avoid catching too broadly (don't use bare `except Exception`), don't use empty catch blocks, don't log and re-throw the same error twice, always clean up resources, write meaningful error messages, and don't silently ignore errors.
Ensure all promises and async operations have error handlers. Use proper error propagation in async chains, handle timeouts explicitly, and avoid unhandled promise rejections which can crash applications.
A good error message explains what happened, provides context (what was being attempted), and suggests how to fix it. Include relevant details like IDs, values, and service names. Avoid generic messages like 'Error occurred'.
Full instructions (SKILL.md)
Source of truth, from wshobson/agents.
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
- Fail Fast: Validate input early, fail quickly
- Preserve Context: Include stack traces, metadata, timestamps
- Meaningful Messages: Explain what happened and how to fix it
- Log Appropriately: Error = log, expected failure = don't spam logs
- Handle at Right Level: Catch where you can meaningfully handle
- Clean Up Resources: Use try-finally, context managers, defer
- Don't Swallow Errors: Log or re-throw, don't silently ignore
- 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 Exceptionhides 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
Related skills
More from wshobson/agents and the wider catalog.
tailwind-design-system
Build production-ready design systems with Tailwind CSS v4, design tokens, and component libraries.
typescript-advanced-types
Master TypeScript's advanced type system: generics, conditional types, mapped types, and utility types for type-safe applications.
nodejs-backend-patterns
Build production-ready Node.js backends with Express/Fastify, middleware patterns, auth, and database integration.
python-performance-optimization
Profile and optimize Python code using cProfile, memory profilers, and performance best practices.
brand-landingpage
Brand-first landing page designer with guided interviews and Stitch-powered iteration.
python-testing-patterns
Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development.