{"data":{"slug":"discovered-512580a8f1f5f4c7a1c686bb91f086293b1d8cac6b7e0c7d","title":"Error Handling","summary":"Implement universal error-handling patterns, including error taxonomy, Result types, error boundaries, structured exceptions, and never-swallow rules. This skill is essential when designing service layers, API responses, or handling external API failures.","url":"https:\/\/skillshunter.net\/skills\/discovered-512580a8f1f5f4c7a1c686bb91f086293b1d8cac6b7e0c7d","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-512580a8f1f5f4c7a1c686bb91f086293b1d8cac6b7e0c7d","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-512580a8f1f5f4c7a1c686bb91f086293b1d8cac6b7e0c7d.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-512580a8f1f5f4c7a1c686bb91f086293b1d8cac6b7e0c7d\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Ensure that errors are treated as values in type signatures, not as side channels. Always include `requestId` in error responses for support correlation. Use libraries like `axios-retry`, `got`, or `tenacity` for HTTP retries instead of rolling your own unless necessary.","instructions":"---\nname: error-handling\nversion: 1.1.0\ndescription: Universal error-handling patterns. Error taxonomy, Result types, error boundaries, structured exceptions, never-swallow rules. Invoke when designing service layers, API responses, or any try\/catch.\n---\n\n# Error Handling\n\n**ALWAYS invoke when adding try\/catch, designing service layers, API error responses, or handling external API failures.**\n\n> The default state of software is broken. Errors are not exceptional \u2014 handling them is the job.\n\n## Core Principles\n\n1. **Errors are values.** Plan for them in the type signature, not as a side channel.\n2. **Throw at boundaries, return at edges.** Internal modules return Results; HTTP layer translates to status codes; user sees a generic message.\n3. **Never swallow.** A `catch` with no log, no rethrow, and no recovery is a bug.\n4. **Fail closed.** On unexpected error, deny \u2014 don't continue with degraded state.\n5. **Distinguish operational from programmer errors.** Operational = expected (network blip, validation). Programmer = bug. They get different treatment.\n\n---\n\n## Error Taxonomy (mandatory)\n\nEvery error you create classifies into one of these:\n\n| Class | Examples | Strategy |\n|---|---|---|\n| **Validation** | Bad input, schema mismatch | Return 4xx with field details; do not log as error |\n| **Authentication** | Missing\/expired\/invalid token | 401, log at info |\n| **Authorization** | Authenticated but not allowed | 403, log at warn (could be probing) |\n| **NotFound** | Resource missing | 404, log at info |\n| **Conflict** | Optimistic lock, duplicate key | 409, log at warn |\n| **RateLimit** | Quota exceeded | 429 + `Retry-After`, log at info |\n| **External** | Upstream API failed | Retry+backoff if idempotent; 502\/503; log at error |\n| **Programmer** | Null deref, type mismatch, switch missed | 500, log at error, alert, fix |\n\nIf the error doesn't fit, you have a new class \u2014 add it deliberately.\n\n---\n\n## Pattern 1 \u2014 Custom Error Classes (TS \/ Python \/ PHP)\n\n### TypeScript\n```ts\n\/\/ lib\/errors.ts\nexport class AppError extends Error {\n  constructor(\n    public readonly code: string,\n    public readonly httpStatus: number,\n    message: string,\n    public readonly cause?: unknown,\n    public readonly meta?: Record<string, unknown>,\n  ) {\n    super(message);\n    this.name = this.constructor.name;\n  }\n}\n\nexport class ValidationError extends AppError {\n  constructor(message: string, fields?: Record<string, string[]>) {\n    super('validation_error', 422, message, undefined, { fields });\n  }\n}\nexport class NotFoundError extends AppError {\n  constructor(resource: string) { super('not_found', 404, `${resource} not found`); }\n}\nexport class UnauthorizedError extends AppError {\n  constructor(message = 'Unauthorized') { super('unauthorized', 401, message); }\n}\nexport class ForbiddenError extends AppError {\n  constructor(message = 'Forbidden') { super('forbidden', 403, message); }\n}\nexport class ConflictError extends AppError {\n  constructor(message: string) { super('conflict', 409, message); }\n}\nexport class ExternalError extends AppError {\n  constructor(service: string, cause: unknown) {\n    super('external_error', 502, `Upstream ${service} failed`, cause);\n  }\n}\n```\n\n### Python\n```python\nclass AppError(Exception):\n    code: str = \"error\"\n    http_status: int = 500\n    def __init__(self, message: str, *, cause: Exception | None = None, meta: dict | None = None):\n        super().__init__(message)\n        self.cause, self.meta = cause, meta or {}\n\nclass ValidationError(AppError):  code, http_status = \"validation_error\", 422\nclass NotFoundError(AppError):    code, http_status = \"not_found\", 404\nclass UnauthorizedError(AppError):code, http_status = \"unauthorized\", 401\nclass ForbiddenError(AppError):   code, http_status = \"forbidden\", 403\nclass ConflictError(AppError):    code, http_status = \"conflict\", 409\nclass ExternalError(AppError):    code, http_status = \"external_error\", 502\n```\n\n### PHP\nUse Laravel's `HttpException` family + custom domain exceptions. Override `Handler::register` to map domain exceptions to HTTP responses.\n\n---\n\n## Pattern 2 \u2014 Result Types (for internal layers)\n\nThrowing across many layers is expensive (TypeScript) and opaque (it's not in the signature). For internal service code, use a Result.\n\n### TypeScript\n```ts\ntype Result<T, E = AppError> =\n  | { ok: true;  data: T }\n  | { ok: false; error: E };\n\nconst ok = <T>(data: T): Result<T> => ({ ok: true, data });\nconst err = <E extends AppError>(error: E): Result<never, E> => ({ ok: false, error });\n\n\/\/ Service returns Result; caller handles both branches\nasync function findUser(id: string): Promise<Result<User>> {\n  const user = await db.user.findById(id);\n  if (!user) return err(new NotFoundError('user'));\n  return ok(user);\n}\n\n\/\/ Caller (route handler) \u2014 throws to be caught by error middleware\nconst result = await findUser(id);\nif (!result.ok) throw result.error;\nreturn result.data;\n```\n\n### Python\n```python\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\nT = TypeVar(\"T\"); E = TypeVar(\"E\")\n\n@dataclass(frozen=True)\nclass Ok(Generic[T]):  data: T\n@dataclass(frozen=True)\nclass Err(Generic[E]): error: E\n\nResult = Ok[T] | Err[E]\n```\n\nOr use `returns` library: `from returns.result import Result, Success, Failure`.\n\n---\n\n## Pattern 3 \u2014 Centralized HTTP Error Handler\n\n### Express\n```ts\n\/\/ errors of type AppError \u2192 mapped; everything else \u2192 500\napp.use((err: unknown, req: Request, res: Response, _next: NextFunction) => {\n  const requestId = res.getHeader('x-request-id');\n  if (err instanceof AppError) {\n    req.log.warn({ err, code: err.code, status: err.httpStatus }, err.message);\n    return res.status(err.httpStatus).json({\n      error: { code: err.code, message: err.message, requestId, ...err.meta },\n    });\n  }\n  \/\/ Unknown \u2014 programmer error, never leak details\n  req.log.error({ err }, 'Unhandled exception');\n  res.status(500).json({ error: { code: 'internal_error', message: 'Internal Server Error', requestId } });\n});\n```\n\n### Next.js \u2014 App Router\nUse `error.tsx` + `global-error.tsx` for client-rendered errors, and a wrapper for Route Handlers:\n\n```ts\n\/\/ app\/api\/_handler.ts\nexport function safeHandler<T extends Request>(fn: (req: T) => Promise<Response>) {\n  return async (req: T): Promise<Response> => {\n    try { return await fn(req); }\n    catch (e) {\n      if (e instanceof AppError) {\n        return Response.json({ error: { code: e.code, message: e.message, ...e.meta } }, { status: e.httpStatus });\n      }\n      logger.error({ err: e }, 'Unhandled');\n      return Response.json({ error: { code: 'internal_error', message: 'Internal Server Error' } }, { status: 500 });\n    }\n  };\n}\n```\n\n### FastAPI\n```python\nfrom fastapi import FastAPI, Request\nfrom fastapi.responses import JSONResponse\n\n@app.exception_handler(AppError)\nasync def app_error_handler(req: Request, exc: AppError):\n    return JSONResponse(\n        {\"error\": {\"code\": exc.code, \"message\": str(exc), **exc.meta}},\n        status_code=exc.http_status,\n    )\n\n@app.exception_handler(Exception)\nasync def unhandled_handler(req: Request, exc: Exception):\n    log.exception(\"unhandled\", request_id=req.headers.get(\"x-request-id\"))\n    return JSONResponse(\n        {\"error\": {\"code\": \"internal_error\", \"message\": \"Internal Server Error\"}},\n        status_code=500,\n    )\n```\n\n---\n\n## Pattern 4 \u2014 Retry with Backoff (External Calls)\n\n```ts\n\/\/ Idempotent operations only. Never retry payments without idempotency keys.\nasync function withRetry<T>(\n  fn: () => Promise<T>,\n  { tries = 3, baseMs = 200, factor = 2, jitter = 0.3 } = {},\n): Promise<T> {\n  let lastErr: unknown;\n  for (let i = 0; i < tries; i++) {\n    try { return await fn(); }\n    catch (e) {\n      lastErr = e;\n      if (i === tries - 1) break;\n      const delay = baseMs * Math.pow(factor, i) * (1 + (Math.random() - 0.5) * 2 * jitter);\n      await new Promise(r => setTimeout(r, delay));\n    }\n  }\n  throw new ExternalError('upstream', lastErr);\n}\n```\n\nFor HTTP retries, use `axios-retry`, `got` (built-in), or `tenacity` (Python). Don't roll your own unless you must.\n\n**Idempotency keys** for non-idempotent operations (POST that creates \/ charges):\n```ts\nawait stripe.charges.create({ amount, customer }, { idempotencyKey: orderId });\n```\n\n---\n\n## Pattern 5 \u2014 Circuit Breaker (External Outages)\n\nWhen upstream is down, fail fast instead of piling up requests:\n\n```ts\nimport CircuitBreaker from 'opossum';\nconst breaker = new CircuitBreaker(callUpstream, {\n  timeout: 3000,\n  errorThresholdPercentage: 50,\n  resetTimeout: 30000,\n});\nbreaker.fallback(() => ({ data: cached, stale: true }));\n```\n\nPython: `pybreaker`. PHP: `ackintosh\/ganesha`.\n\n---\n\n## Pattern 6 \u2014 Async \/ Promise Hygiene\n\n```ts\n\/\/ WRONG \u2014 unhandled rejection crashes the process (Node 15+)\nsomePromise();\n\n\/\/ CORRECT \u2014 always handle, even if just to log\nsomePromise().catch(err => logger.error({ err }, 'background task failed'));\n\n\/\/ Promise.all rejects on first failure \u2014 for partial success use allSettled\nconst results = await Promise.allSettled([fetchA(), fetchB(), fetchC()]);\nconst failures = results.filter(r => r.status === 'rejected');\nif (failures.length > 0) logger.warn({ failures }, 'partial failure');\n```\n\nCatch handler at process level (defense in depth):\n```ts\nprocess.on('unhandledRejection', (reason) => {\n  logger.fatal({ reason }, 'Unhandled rejection');\n  process.exit(1);\n});\nprocess.on('uncaughtException', (err) => {\n  logger.fatal({ err }, 'Uncaught exception');\n  process.exit(1);\n});\n```\n\n---\n\n## Anti-Patterns\n\n| Anti-pattern | Why it's bad | Fix |\n|---|---|---|\n| `try { ... } catch {}` | Silent failure | Log + rethrow or recover deliberately |\n| `catch (e) { console.log(e) }` | No structured context | Use logger; include `request_id`, `user_id` |\n| `catch (e) { throw new Error(e.message) }` | Loses stack trace | `throw new AppError(..., e)` (preserve cause) |\n| `if (err) return null` | Caller can't distinguish \"no result\" from \"failed\" | Result type |\n| Returning `{ error: 'something' }` from a function | Convention drift, untyped | Result type or throw |\n| Catching `Error` to coerce | Hides bugs | Catch specific classes |\n| Generic 500 response with raw stack | Info disclosure | Log full, return generic message + requestId |\n| Retrying non-idempotent calls | Double-charge \/ double-create | Idempotency keys |\n| Retrying without backoff | DoS your own upstream | Exponential + jitter |\n\n## API Error Response Shape (Standardize)\n\n```json\n{\n  \"error\": {\n    \"code\": \"validation_error\",\n    \"message\": \"Invalid input\",\n    \"fields\": {\n      \"email\": [\"must be a valid email\"],\n      \"age\": [\"must be at least 13\"]\n    },\n    \"requestId\": \"req_abc123\"\n  }\n}\n```\n\nStable contract: client code can switch on `code`. Always include `requestId` so support can correlate with logs.\n\n## Pre-Commit Checklist\n\n- [ ] No empty `catch` blocks\n- [ ] Every `catch` either logs+rethrows, recovers deliberately, or transforms to `AppError`\n- [ ] Service-layer functions that can fail return `Result` or throw `AppError`\n- [ ] HTTP layer has a single error mapper; routes do not stringify exceptions\n- [ ] External calls have retry + backoff (if idempotent) or idempotency keys\n- [ ] No raw stack traces in API responses\n- [ ] Process-level `unhandledRejection` \/ `uncaughtException` handlers exist (Node)\n\n## See Also\n\n- `tool-resilience` \u2014 recovering from the AGENT's own tool failures (fetch bot-blocks, stale edits, timeouts); includes the Cloudflare 520 \/ HTTP 444 User-Agent recovery\n- `observability` \u2014 what to log on errors\n- `security-baseline` \u2014 A09 logging, A05 config (don't leak stack traces)\n- Stack `api-security-*` \u2014 error mapping in framework handlers\n","use_cases":["Designing service layers with structured error handling","Creating API responses with consistent error codes and messages","Handling external API failures with retry and backoff strategies","Implementing custom error classes in TypeScript, Python, or PHP","Differentiating between operational and programmer errors for appropriate handling"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/0x57-1\/start-vibing-stacks\/blob\/6e398b34c4dfe73ac8f809216b218856b8e02ff4\/stacks\/_shared\/skills\/error-handling\/SKILL.md","source_commit":"6e398b34c4dfe73ac8f809216b218856b8e02ff4","license":null,"version":null,"listing_approved_at":"2026-12-03","created_at":"2026-12-02T09:11:13.000000Z","updated_at":"2026-12-03T16:20:08.000000Z","seo_title":"Error Handling Patterns for Software Development","seo_description":"Learn and apply universal error-handling practices, including error taxonomy, Result types, and structured exceptions. Essential for designing robust service layers and a","seo_keywords":["error handling","error taxonomy","result types","structured exceptions","never-swallow rule","API error responses","custom error classes","software development"]}}