Design error handling strategies for TypeScript and Python applications — exception hierarchies, Result/Either types, retry patterns, error boundaries, and structured error logging. Use when designing error handling architecture, choosing between exceptions and Result types, implementing retry logic, or building error recovery flows. Activate on "error handling", "exception hierarchy", "Result type", "retry pattern", "circuit breaker", "error boundary", "Pokemon exception". NOT for debugging specific runtime errors, logging infrastructure setup, or monitoring/alerting configuration.
Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
Instruções da origem · Visualização somente leitura
license
Apache-2.0
name
error-handling-patterns
description
Design error handling strategies for TypeScript and Python applications — exception hierarchies, Result/Either types, retry patterns, error boundaries, and structured error logging. Use when designing error handling architecture, choosing between exceptions and Result types, implementing retry logic, or building error recovery flows. Activate on "error handling", "exception hierarchy", "Result type", "retry pattern", "circuit breaker", "error boundary", "Pokemon exception". NOT for debugging specific runtime errors, logging infrastructure setup, or monitoring/alerting configuration.
{"category":"DevOps & Site Reliability","tags":["error","handling","patterns","error-handling","exception-hierarchy"],"pairs-with":[{"skill":"typescript-advanced-patterns","reason":"Result/Either types and discriminated unions implement type-safe error handling in TS"},{"skill":"logging-observability","reason":"Structured error logging with correlation IDs enables effective error tracking and debugging"},{"skill":"background-job-orchestrator","reason":"Retry patterns and dead letter queues are error handling applied to job processing"}]}
Design error handling strategies that make failures explicit, recoverable, and debuggable. The central skill is matching error handling style to error semantics: not all errors are equal, and treating them equally produces systems that are equally bad at handling all of them.
When to Use
✅ Use for:
Choosing between exceptions, Result types, or error codes for a domain
Designing typed error hierarchies in TypeScript or Python
Implementing retry logic with backoff, jitter, and circuit breaking
Building React error boundaries and graceful degradation
Structuring error information for both users and developers
Python exception chaining and __cause__ / __context__ semantics
❌ NOT for:
Debugging a specific runtime error (use debugger or domain skill)
Consult references/error-hierarchy-examples.md for Python equivalents, Result type implementations, and full hierarchy patterns.
Result Type Pattern (TypeScript)
When errors are expected outcomes of operations (parsing, API calls, DB queries), use Result instead of throw:
typeResult<T, E = AppError> =
| { ok: true; value: T }
| { ok: false; error: E };
// Helpersconst ok = <T>(value: T): Result<T, never> => ({ ok: true, value });
const err = <E>(error: E): Result<never, E> => ({ ok: false, error });
// Usage — caller is forced to handle both casesasyncfunctionfetchUser(id: string): Promise<Result<User, NotFoundError | NetworkError>> {
try {
const user = await db.users.findById(id);
if (!user) returnerr(newNotFoundError('User', id));
returnok(user);
} catch (e) {
returnerr(newNetworkError('DB unavailable', { cause: e }));
}
}
// At call site — no silent failuresconst result = awaitfetchUser(userId);
if (!result.ok) {
if (result.errorinstanceofNotFoundError) return res.status(404).json(...);
return res.status(500).json(...);
}
const user = result.value; // typed, safe
React Error Boundaries
Error boundaries catch render-time exceptions. They do NOT catch async errors (fetch failures, setTimeout, event handlers).
classRouteErrorBoundaryextendsReact.Component<Props, State> {
staticgetDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
// Log to error tracking, not console.error in production
logger.error('Render error', { error, componentStack: info.componentStack });
}
render() {
if (this.state.hasError) {
return<ErrorFallbackerror={this.state.error}onRetry={this.reset} />;
}
returnthis.props.children;
}
}
Place boundaries at route level (one per page) and around isolated expensive subtrees (charts, rich editors). Do not wrap every component — too granular breaks the benefit.
Python: Exception Chaining
Python's raise X from Y syntax preserves causal chains — use it always when re-raising:
classAppError(Exception):
"""Base error. All domain errors subclass this."""def__init__(self, message: str, code: str, status: int = 500):
super().__init__(message)
self.code = code
self.status = status
classDatabaseError(AppError):
def__init__(self, operation: str, cause: Exception):
super().__init__(f"DB error during {operation}", "DB_ERROR", 503)
self.__cause__ = cause # explicit chain# In application codetry:
result = db.execute(query)
except psycopg2.OperationalError as e:
raise DatabaseError("user_fetch", e) from e # preserves full traceback
Structured Error Logging
Log errors with enough context to diagnose without reading code:
// Good: structured, queryable, developer-oriented
logger.error('Payment processing failed', {
error: {
code: error.code,
message: error.message,
stack: error.stack,
},
context: {
userId,
orderId,
amount,
paymentProvider,
attempt: retryCount,
},
correlation: { requestId, traceId },
});
// Then surface a sanitized message to the user// NEVER leak error.message to users — it may contain internalsreturn res.status(500).json({
error: 'Payment could not be processed. Please try again.',
errorId: requestId, // so support can look it up
});
Anti-Patterns
Anti-Pattern: Pokemon Exception Handling
Novice: "Wrap everything in try/catch and log the error. At least it won't crash."
Expert: Catching all exceptions unconditionally ("gotta catch 'em all") hides programmer errors, masks resource leaks, and converts loud failures into silent corruption. The system appears healthy while data is being silently dropped.
// Wrong — swallows everything including programming errorstry {
awaitprocessOrder(order);
} catch (e) {
console.error('something went wrong', e); // lost forever
}
// Right — catch only what you can handle, let the rest propagatetry {
awaitprocessOrder(order);
} catch (e) {
if (e instanceofRateLimitError) {
await queue.requeue(order, { delay: e.retryAfterMs });
return;
}
// programming errors, unexpected DB errors — let them crashthrow e;
}
Detection: catch (e) { }, catch (e) { log(e) } with no rethrow, except Exception as e: pass in Python. Any catch block with no condition and no rethrow.
Timeline: This has always been wrong. Renewed urgency in async/await era (2017+) because swallowed promise rejections are even harder to detect than swallowed sync exceptions.
Anti-Pattern: Stringly-Typed Errors
Novice: "I'll put the error type in the message string: throw new Error('NOT_FOUND: User 123')"
Expert: String-based error types force callers to parse strings, break under refactoring, provide no IDE support, and make exhaustive matching impossible. Callers pattern-match on strings that drift as the codebase evolves.
// Wrong — caller must parse strings, breaks silently on renamethrownewError(`RATE_LIMIT: retry after ${ms}ms`);
// Caller: if (error.message.startsWith('RATE_LIMIT')) { ... }// Right — typed, refactor-safe, IDE-navigablethrownewRateLimitError(ms);
// Caller: if (error instanceof RateLimitError) { ... error.retryAfterMs ... }
LLM mistake: LLMs trained on StackOverflow examples frequently generate stringly-typed errors because SO answers prioritize brevity over correctness. Error codes as strings look concise in tutorials.
Detection: instanceof Error checks everywhere, string .startsWith() or .includes() in catch blocks, error codes stored in message field rather than a dedicated property.
References
references/retry-patterns.md — Consult when implementing retry logic: exponential backoff formulas, full vs equal jitter, circuit breaker state machine, dead letter queues
references/error-hierarchy-examples.md — Consult for complete TypeScript and Python typed error class examples, Result monad implementations, and error boundary patterns