ER

error-handling

Design and implement resilient error handling, retry policies, and circuit breakers.

Install

mkdir -p .claude/skills/error-handling-jnpiyush && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/10693" && unzip -o skill.zip -d .claude/skills/error-handling-jnpiyush && rm skill.zip

Installs to .claude/skills/error-handling-jnpiyush

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Implement robust error handling with exceptions, retry logic, circuit breakers, and graceful degradation. Use when designing error handling strategies, implementing retry policies, adding circuit breakers, configuring timeouts, or building health check endpoints.
263 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Advanced

Key capabilities

  • Implement retry logic
  • Configure circuit breakers
  • Build health check endpoints
  • Design error handling strategies

How it works

The skill guides the implementation of resilience patterns like retries, circuit breakers, and timeouts to ensure system stability and clear error reporting.

Inputs & outputs

You give it
Failure scenario
You get back
Resilient error handling implementation

When to use error-handling

  • Design retry logic
  • Implement circuit breakers
  • Build health check endpoints

About this skill

Error Handling

Purpose: Handle failures gracefully with logging, retries, and circuit breakers. Goal: No silent failures, clear error messages, system resilience. Note: For language-specific implementations, see C# Development or Python Development.


When to Use This Skill

  • Designing error handling strategies
  • Implementing retry policies with backoff
  • Adding circuit breakers for external services
  • Configuring request timeouts
  • Building health check endpoints

Prerequisites

  • Understanding of exception hierarchies in target language
  • Resilience library available

Rationalization Table

Error handling is where shortcuts hide. Push back against these.

RationalizationReality
"I'll catch Exception / except: here, narrower types take too long."Bare catches swallow the bugs you most need to see, including programmer errors. Catch the specific exception types you can actually handle.
"This error can't happen in practice."Then the right move is to fail loudly when it does, not to silently swallow it. Log + re-raise, do not return a default.
"I'll log and continue so the request still succeeds."A partially-completed request that returns 200 is harder to debug than a clean 500. Decide explicitly whether to fail the request or to degrade.
"Retries will paper over the transient failure."Retries without backoff or budget make outages worse. Always pair retries with exponential backoff, jitter, and a circuit breaker.
"Adding context to the error is noise."The agent or operator reading the log has no other context. Include the operation, the identifiers, and the upstream cause.
"The framework already handles this."Frameworks handle transport errors. They do not handle your domain invariants. Domain errors need explicit types and explicit handling.

Decision Tree

Handling an error?
+- Expected failure (validation, not-found)?
| - Return error result/status code, don't throw
+- Unexpected failure (network, I/O, timeout)?
| +- Transient? -> Retry with exponential backoff
| | - Still failing after retries? -> Circuit breaker
| - Permanent? -> Log + return error response
+- What to catch?
| +- Specific exception -> catch specific, handle specifically
| +- Base exception -> only at top-level boundaries
| - NEVER catch and swallow silently
+- Error response format?
| +- API? -> RFC 7807 Problem Details
| - UI? -> User-friendly message + log technical details
- Logging?
 - Always include: correlation ID, exception type, stack trace, context

Exception Handling

Custom Exception Types

Define Specific Exceptions:

Exception Hierarchy:
 AppException (base)
 +- ValidationException
 +- NotFoundException 
 +- UnauthorizedException
 +- ForbiddenException
 - ExternalServiceException

Benefits:

  • Catch specific errors
  • Provide context in exception
  • Different handling per type
  • Clear error messages

Try-Catch-Finally Pattern

function processPayment(amount, paymentMethod):
 try:
 # Attempt operation
 validatePaymentMethod(paymentMethod)
 chargeResult = paymentGateway.charge(amount, paymentMethod)
 
 # Log success
 logger.info("Payment processed", {amount, paymentMethod})
 
 return chargeResult
 
 catch ValidationException as error:
 # Handle validation errors
 logger.warn("Invalid payment method", {error, paymentMethod})
 throw error
 
 catch NetworkException as error:
 # Handle network errors with retry
 logger.error("Payment gateway unavailable", {error})
 throw ExternalServiceException("Payment service temporarily unavailable")
 
 finally:
 # Always execute (cleanup resources)
 releasePaymentLock(paymentMethod)

Global Error Handler

Centralized Error Handling:

# HTTP API Error Handler
function handleHttpError(error, request, response):
 # Log error with context
 logger.error("Request failed", {
 error: error.message,
 stack: error.stack,
 requestId: request.id,
 path: request.path,
 method: request.method
 })
 
 # Map exception to HTTP status
 statusCode = mapExceptionToStatusCode(error)
 
 # Return user-friendly response
 return response.status(statusCode).json({
 error: error.userMessage,
 requestId: request.id,
 timestamp: currentTime()
 })

function mapExceptionToStatusCode(error):
 if error is NotFoundException: return 404
 if error is ValidationException: return 400
 if error is UnauthorizedException: return 401
 if error is ForbiddenException: return 403
 if error is ExternalServiceException: return 503
 return 500 # Internal Server Error

Core Rules

  1. Fail Fast - Detect errors at the earliest point and surface them immediately; do not let invalid state propagate
  2. Catch Specific Exceptions - Handle the narrowest exception type possible; never catch base Exception except at top-level boundaries
  3. Never Swallow Silently - Every catch block MUST log or re-throw; empty catch blocks hide production bugs
  4. Log With Context - Include correlation ID, operation name, input parameters, and stack trace in every error log entry
  5. Separate User vs Internal Messages - Return safe, actionable messages to users; log full technical details internally
  6. Use Resilience Patterns - Apply retry with exponential backoff for transient failures; circuit breakers for cascading failure prevention
  7. Timeout Everything - Every external call (HTTP, database, queue) MUST have an explicit timeout configured
  8. Validate Inputs at Boundaries - Check all external input at API/service boundaries; return 400-level errors for bad input, not 500
  9. Design for Partial Failure - Distributed systems fail partially; use fallbacks, bulkheads, and graceful degradation
  10. Test Error Paths - Write tests for failure scenarios, not just happy paths; verify retry, timeout, and fallback behavior

Resilience Patterns

PatternUse CaseExample
RetryTransient failuresNetwork timeouts, rate limits
Circuit BreakerPrevent cascading failuresExternal service calls
FallbackProvide alternativeDefault values, cached data
TimeoutPrevent hangingLong-running operations
BulkheadIsolate resourcesSeparate thread pools per service
Rate LimitingProtect from overloadAPI throttling

Anti-Patterns

[FAIL] Swallow Exceptions:

try:
 riskyOperation()
catch:
 # Do nothing - ERROR! No one knows it failed

[FAIL] Generic Catch-All:

try:
 operation()
catch Exception:
 return null # Hides what went wrong

[FAIL] Exception for Flow Control:

try:
 user = database.findUser(id)
catch NotFoundException:
 # Using exceptions for normal flow - BAD
 user = createNewUser(id)

[PASS] Proper Error Handling:

try:
 user = database.findUser(id)
catch NotFoundException as error:
 logger.warn("User not found", {id})
 throw error # Re-throw, don't hide
catch DatabaseException as error:
 logger.error("Database error", {error, id})
 throw ServiceUnavailableException("User service temporarily unavailable")

Resilience Patterns Summary

Resilience Stack (Apply Multiple Patterns):

 -------------------------------------
 | Rate Limiting (Protect your service)|
 -------------------------------------
 (down)
 -------------------------------------
 | Timeout (Prevent hanging) |
 -------------------------------------
 (down)
 -------------------------------------
 | Circuit Breaker (Fail fast) |
 -------------------------------------
 (down)
 -------------------------------------
 | Retry (Handle transient failures) |
 -------------------------------------
 (down)
 -------------------------------------
 | Fallback (Provide alternative) |
 -------------------------------------

Resources

Resilience Libraries:

  • .NET: Polly, Microsoft.Extensions.Resilience
  • Python: tenacity, resilience4py
  • Node.js: opossum (circuit breaker), async-retry
  • Java: Resilience4j, Hystrix (deprecated)
  • Go: go-resilience, go-retry

Patterns:


See Also: Skills.md - AGENTS.md

Last Updated: January 27, 2026

Troubleshooting

IssueSolution
Retry storm overwhelming serviceAdd exponential backoff with jitter, set max retry count
Circuit breaker stuck openCheck half-open state configuration, verify health endpoint responds
Swallowed exceptions hiding bugsAlways log exceptions before fallback, use structured logging with stack traces

References

When not to use it

  • Silent failure handling
  • Ignoring domain-specific errors

Prerequisites

Resilience library

Limitations

  • Requires language-specific resilience libraries
  • Manual configuration of backoff/jitter

How it compares

It emphasizes explicit error handling and resilience patterns over silent failures or generic exception swallowing.

Compared to similar skills

error-handling side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
error-handling (this skill)02moNo flagsAdvanced
python-error-handling12moNo flagsIntermediate
debugging-streamlit75moReviewIntermediate
effect-patterns-error-handling17moNo flagsAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jnPiyush

View all by jnPiyush

ux-ui-design

jnPiyush

Design user experiences with wireframing, prototyping, user flows, accessibility, and production-ready HTML prototypes. Use when creating wireframes, building interactive prototypes, designing user flows, implementing accessibility standards, or producing HTML/CSS design deliverables.

00

copilot-studio-agents

jnPiyush

Design Microsoft Copilot Studio agents (formerly Power Virtual Agents) -- topics, trigger phrases, generative answers, knowledge sources, connector and MCP actions, authentication, channels, and agent flows -- so an agent can author the conversational logic that ships as a Bot component inside a Pow

00

verification-before-completion

jnPiyush

Block false completion claims. Force the agent to identify the claim, run the exact verification command, read the actual output, compare against the claim, and only then report. Use whenever an agent is about to say "done", "fixed", "tests pass", "deployed", "loop complete", or close an issue.

00

configuration

jnPiyush

Implement configuration management patterns including environment variables, secrets, feature flags, and validation strategies. Use when setting up app configuration, managing environment-specific settings, implementing feature flags, storing secrets securely, or validating configuration at startup.

00

docx

jnPiyush

Read, write, and transform Microsoft Word .docx files. Use when extracting text or tables from Word documents, generating reports from templates, applying styles, inserting images, building tables, or converting Markdown/HTML to Word.

00

mcp-apps-development

jnPiyush

Build MCP Apps (ext-apps) that render interactive UI inside conversational AI clients. Use when creating visual tool outputs, interactive dashboards, form-based tools, or rich media experiences in MCP-compatible hosts like Claude Desktop, VS Code Copilot Chat, or other MCP clients that support the A

00

You might also like

python-error-handling

wshobson

Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robust APIs.

145

debugging-streamlit

streamlit

Debug Streamlit frontend and backend changes using make debug with hot-reload. Use when testing code changes, investigating bugs, checking UI behavior, or needing screenshots of the running app.

733

effect-patterns-error-handling

PaulJPhilp

Effect-TS patterns for Error Handling. Use when working with error handling in Effect-TS applications.

12

effect-patterns-scheduling

PaulJPhilp

Effect-TS patterns for Scheduling. Use when working with scheduling in Effect-TS applications.

12

guidewire-local-dev-loop

jeremylongshore

Configure local Guidewire development workflow with Guidewire Studio, Gosu debugging, and hot reload capabilities. Use when setting up development environment, configuring IDE, or optimizing dev workflow. Trigger with phrases like "guidewire local dev", "guidewire studio setup", "gosu development", "guidewire debugging", "configure guidewire ide".

02

nextjs-server-side-error-debugging

blader

Debug getServerSideProps and getStaticProps errors in Next.js. Use when: (1) Page shows generic error but browser console is empty, (2) API routes return 500 with no details, (3) Server-side code fails silently, (4) Error only occurs on refresh not client navigation. Check terminal/server logs instead of browser for actual error messages.

11

Search skills

Search the agent skills registry