{"slug":"error-handling-2","title":"error-handling","summary":"Patterns for robust error handling across TypeScript, Python, and Go. Covers typed errors, error boundaries, retries, circuit breakers, and user-facing error messages. Use when designing error types, retries, circuit breakers, or user-facing failure messages in TypeScript, Python","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:04.123989Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: error-handling\ndescription: Patterns for robust error handling across TypeScript, Python, and Go. Covers typed errors, error boundaries, retries, circuit breakers, and user-facing error messages. Use when designing error types, retries, circuit breakers, or user-facing failure messages in TypeScript, Python, or Go.\nmetadata:\norigin: ECC</h2>\n<h1>Error Handling Patterns</h1>\n<p>Consistent, robust error handling patterns for production applications.</p>\n<h2>When to Activate</h2>\n<ul>\n<li>Designing error types or exception hierarchies for a new module or service</li>\n<li>Adding retry logic or circuit breakers for unreliable external dependencies</li>\n<li>Reviewing API endpoints for missing error handling</li>\n<li>Implementing user-facing error messages and feedback</li>\n<li>Debugging cascading failures or silent error swallowing</li>\n</ul>\n<h2>Core Principles</h2>\n<ol>\n<li><strong>Fail fast and loudly</strong> — surface errors at the boundary where they occur; don't bury them</li>\n<li><strong>Typed errors over string messages</strong> — errors are first-class values with structure</li>\n<li><strong>User messages ≠ developer messages</strong> — show friendly text to users, log full context server-side</li>\n<li><strong>Never swallow errors silently</strong> — every <code>catch</code> block must either handle, re-throw, or log</li>\n<li><strong>Errors are part of your API contract</strong> — document every error code a client may receive</li>\n</ol>\n<h2>TypeScript / JavaScript</h2>\n<h3>Typed Error Classes</h3>\n<pre><code>// Define an error hierarchy for your domain\nexport class AppError extends Error {\n  constructor(\n    message: string,\n    public readonly code: string,\n    public readonly statusCode: number = 500,\n    public readonly details?: unknown,\n  ) {\n    super(message)\n    this.name = this.constructor.name\n    // Maintain correct prototype chain in transpiled ES5 JavaScript.\n    // Required for `instanceof` checks (e.g., `error instanceof NotFoundError`)\n    // to work correctly when extending the built-in Error class.\n    Object.setPrototypeOf(this, new.target.prototype)\n  }\n}\n\nexport class NotFoundError extends AppError {\n  constructor(resource: string, id: string) {\n    super(`${resource} not found: ${id}`, 'NOT_FOUND', 404)\n  }\n}\n\nexport class ValidationError extends AppError {\n  constructor(message: string, details: { field: string; message: string }[]) {\n    super(message, 'VALIDATION_ERROR', 422, details)\n  }\n}\n\nexport class UnauthorizedError extends AppError {\n  constructor(reason = 'Authentication required') {\n    super(reason, 'UNAUTHORIZED', 401)\n  }\n}\n\nexport class RateLimitError extends AppError {\n  constructor(public readonly retryAfterMs: number) {\n    super('Rate limit exceeded', 'RATE_LIMITED', 429)\n  }\n}\n</code></pre>\n<h3>Result Pattern (no-throw style)</h3>\n<p>For operations where failure is expected and common (parsing, external calls):</p>\n<pre><code>type Result&lt;T, E = AppError&gt; =\n  | { ok: true; value: T }\n  | { ok: false; error: E }\n\nfunction ok&lt;T&gt;(value: T): Result&lt;T&gt; {\n  return { ok: true, value }\n}\n\nfunction err&lt;E&gt;(error: E): Result&lt;never, E&gt; {\n  return { ok: false, error }\n}\n\n// Usage\nasync function fetchUser(id: string): Promise&lt;Result&lt;User&gt;&gt; {\n  try {\n    const user = await db.users.findUnique({ where: { id } })\n    if (!user) return err(new NotFoundError('User', id))\n    return ok(user)\n  } catch (e) {\n    return err(new AppError('Database error', 'DB_ERROR'))\n  }\n}\n\nconst result = await fetchUser('abc-123')\nif (!result.ok) {\n  // TypeScript knows result.error here\n  logger.error('Failed to fetch user', { error: result.error })\n  return\n}\n// TypeScript knows result.value here\nconsole.log(result.value.email)\n</code></pre>\n<h3>API Error Handler (Next.js / Express)</h3>\n<pre><code>import { NextRequest, NextResponse } from 'next/server'\n\nfunction handleApiError(error: unknown): NextResponse {\n  // Known application error\n  if (error instanceof AppError) {\n    return NextResponse.json(\n      {\n        error: {\n          code: error.code,\n          message: error.message,\n          ...(error.details ? { details: error.details } : {}),\n        },\n      },\n      { status: error.statusCode },\n    )\n  }\n\n  // Zod validation error\n  if (error instanceof z.ZodError) {\n    return NextResponse.json(\n      {\n        error: {\n          code: 'VALIDATION_ERROR',\n          message: 'Request validation failed',\n          details: error.issues.map(i =&gt; ({\n            field: i.path.join('.'),\n            message: i.message,\n          })),\n        },\n      },\n      { status: 422 },\n    )\n  }\n\n  // Unexpected error — log details, return generic message\n  console.error('Unexpected error:', error)\n  return NextResponse.json(\n    { error: { code: 'INTERNAL_ERROR', message: 'An unexpected error occurred' } },\n    { status: 500 },\n  )\n}\n\nexport async function POST(req: NextRequest) {\n  try {\n    // ... handler logic\n  } catch (error) {\n    return handleApiError(error)\n  }\n}\n</code></pre>\n<h3>React Error Boundary</h3>\n<pre><code>import { Component, ErrorInfo, ReactNode } from 'react'\n\ninterface Props {\n  fallback: ReactNode\n  onError?: (error: Error, info: ErrorInfo) =&gt; void\n  children: ReactNode\n}\n\ninterface State {\n  hasError: boolean\n  error: Error | null\n}\n\nexport class ErrorBoundary extends Component&lt;Props, State&gt; {\n  state: State = { hasError: false, error: null }\n\n  static getDerivedStateFromError(error: Error): State {\n    return { hasError: true, error }\n  }\n\n  componentDidCatch(error: Error, info: ErrorInfo) {\n    this.props.onError?.(error, info)\n    console.error('Unhandled React error:', error, info)\n  }\n\n  render() {\n    if (this.state.hasError) return this.props.fallback\n    return this.props.children\n  }\n}\n\n// Usage\n&lt;ErrorBoundary fallback={&lt;p&gt;Something went wrong. Please refresh.&lt;/p&gt;}&gt;\n  &lt;MyComponent /&gt;\n&lt;/ErrorBoundary&gt;\n</code></pre>\n<h2>Python</h2>\n<h3>Custom Exception Hierarchy</h3>\n<pre><code>class AppError(Exception):\n    \"\"\"Base application error.\"\"\"\n    def __init__(self, message: str, code: str, status_code: int = 500):\n        super().__init__(message)\n        self.code = code\n        self.status_code = status_code\n\nclass NotFoundError(AppError):\n    def __init__(self, resource: str, id: str):\n        super().__init__(f\"{resource} not found: {id}\", \"NOT_FOUND\", 404)\n\nclass ValidationError(AppError):\n    def __init__(self, message: str, details: list[dict] | None = None):\n        super().__init__(message, \"VALIDATION_ERROR\", 422)\n        self.details = details or []\n</code></pre>\n<h3>FastAPI Global Exception Handler</h3>\n<pre><code>from fastapi import FastAPI, Request\nfrom fastapi.responses import JSONResponse\n\napp = FastAPI()\n\n@app.exception_handler(AppError)\nasync def app_error_handler(request: Request, exc: AppError) -&gt; JSONResponse:\n    return JSONResponse(\n        status_code=exc.status_code,\n        content={\"error\": {\"code\": exc.code, \"message\": str(exc)}},\n    )\n\n@app.exception_handler(Exception)\nasync def generic_error_handler(request: Request, exc: Exception) -&gt; JSONResponse:\n    # Log full details, return generic message\n    logger.exception(\"Unexpected error\", exc_info=exc)\n    return JSONResponse(\n        status_code=500,\n        content={\"error\": {\"code\": \"INTERNAL_ERROR\", \"message\": \"An unexpected error occurred\"}},\n    )\n</code></pre>\n<h2>Go</h2>\n<h3>Sentinel Errors and Error Wrapping</h3>\n<pre><code>package domain\n\nimport \"errors\"\n\n// Sentinel errors for type-checking\nvar (\n    ErrNotFound    = errors.New(\"not found\")\n    ErrUnauthorized = errors.New(\"unauthorized\")\n    ErrConflict     = errors.New(\"conflict\")\n)\n\n// Wrap errors with context — never lose the original\nfunc (r *UserRepository) FindByID(ctx context.Context, id string) (*User, error) {\n    user, err := r.db.QueryRow(ctx, \"SELECT * FROM users WHERE id = $1\", id)\n    if errors.Is(err, sql.ErrNoRows) {\n        return nil, fmt.Errorf(\"user %s: %w\", id, ErrNotFound)\n    }\n    if err != nil {\n        return nil, fmt.Errorf(\"querying user %s: %w\", id, err)\n    }\n    return user, nil\n}\n\n// At the handler level, unwrap to determine response\nfunc (h *Handler) GetUser(w http.ResponseWriter, r *http.Request) {\n    user, err := h.service.GetUser(r.Context(), chi.URLParam(r, \"id\"))\n    if err != nil {\n        switch {\n        case errors.Is(err, domain.ErrNotFound):\n            writeError(w, http.StatusNotFound, \"not_found\", err.Error())\n        case errors.Is(err, domain.ErrUnauthorized):\n            writeError(w, http.StatusForbidden, \"forbidden\", \"Access denied\")\n        default:\n            slog.Error(\"unexpected error\", \"err\", err)\n            writeError(w, http.StatusInternalServerError, \"internal_error\", \"An unexpected error occurred\")\n        }\n        return\n    }\n    writeJSON(w, http.StatusOK, user)\n}\n</code></pre>\n<h2>Retry with Exponential Backoff</h2>\n<pre><code>interface RetryOptions {\n  maxAttempts?: number\n  baseDelayMs?: number\n  maxDelayMs?: number\n  retryIf?: (error: unknown) =&gt; boolean\n}\n\nasync function withRetry&lt;T&gt;(\n  fn: () =&gt; Promise&lt;T&gt;,\n  options: RetryOptions = {},\n): Promise&lt;T&gt; {\n  const {\n    maxAttempts = 3,\n    baseDelayMs = 500,\n    maxDelayMs = 10_000,\n    retryIf = () =&gt; true,\n  } = options\n\n  let lastError: unknown\n\n  for (let attempt = 1; attempt &lt;= maxAttempts; attempt++) {\n    try {\n      return await fn()\n    } catch (error) {\n      lastError = error\n      if (attempt === maxAttempts || !retryIf(error)) throw error\n\n      const jitter = Math.random() * baseDelayMs\n      const delay = Math.min(baseDelayMs * 2 ** (attempt - 1) + jitter, maxDelayMs)\n      await new Promise(resolve =&gt; setTimeout(resolve, delay))\n    }\n  }\n\n  throw lastError\n}\n\n// Usage: retry transient network errors, not 4xx\nconst data = await withRetry(() =&gt; fetch('/api/data').then(r =&gt; r.json()), {\n  maxAttempts: 3,\n  retryIf: (error) =&gt; !(error instanceof AppError &amp;&amp; error.statusCode &lt; 500),\n})\n</code></pre>\n<h2>User-Facing Error Messages</h2>\n<p>Map error codes to human-readable messages. Keep technical details out of user-visible text.</p>\n<pre><code>const USER_ERROR_MESSAGES: Record&lt;string, string&gt; = {\n  NOT_FOUND: 'The requested item could not be found.',\n  UNAUTHORIZED: 'Please sign in to continue.',\n  FORBIDDEN: \"You don't have permission to do that.\",\n  VALIDATION_ERROR: 'Please check your input and try again.',\n  RATE_LIMITED: 'Too many requests. Please wait a moment and try again.',\n  INTERNAL_ERROR: 'Something went wrong on our end. Please try again later.',\n}\n\nexport function getUserMessage(code: string): string {\n  return USER_ERROR_MESSAGES[code] ?? USER_ERROR_MESSAGES.INTERNAL_ERROR\n}\n</code></pre>\n<h2>Error Handling Checklist</h2>\n<p>Before merging any code that touches error handling:</p>\n<ul>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Every <code>catch</code> block handles, re-throws, or logs — no silent swallowing</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> API errors follow the standard envelope <code>{ error: { code, message } }</code></li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> User-facing messages contain no stack traces or internal details</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Full error context is logged server-side</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Custom error classes extend a base <code>AppError</code> with a <code>code</code> field</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Async functions surface errors to callers — no fire-and-forget without fallback</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> Retry logic only retries retriable errors (not 4xx client errors)</li>\n<li><input disabled=\"disabled\" type=\"checkbox\"> React components are wrapped in <code>ErrorBoundary</code> for rendering errors</li>\n</ul>\n","files":[{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":10984,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:53:28.442247Z","sha256":"C535AABB7FCA3CB67E7598075BCEE3B95C8680019291501E9C907320FC298FC0","sizeBytes":5081},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/error-handling","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"F518DEA54D3EF02795D22E98071C6A5410A2347FE404BE2436027795BFA59F13","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T16:54:14.6426Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/error-handling"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}