[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7F945K8R2XPYA8GBC8478TC":3,"skill-same:01M7F945K8R2XPYA8GBC8478TC":80},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":6,"ownerHtmlUrl":45,"ownerBlogUrl":6,"ownerDescription":46,"updatedAt":47,"install":48,"resources":61},"01M7F945K8R2XPYA8GBC8478TC","error-handling",null,"Use when designing the reaction to a class of failures — typed error taxonomies, retry\u002Fbackoff\u002Ftimeout policy, circuit breakers, React\u002FNext error boundaries, and the user-message vs operator-log split. NOT diagnosing one specific crash (that is debug), NOT logs\u002Fmetrics\u002Ftraces (that is observability), NOT the wire error envelope (that is api-design).","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Ferror-handling\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: error-handling\ndescription: \"Use when designing the reaction to a class of failures — typed error taxonomies, retry\u002Fbackoff\u002Ftimeout policy, circuit breakers, React\u002FNext error boundaries, and the user-message vs operator-log split. NOT diagnosing one specific crash (that is debug), NOT logs\u002Fmetrics\u002Ftraces (that is observability), NOT the wire error envelope (that is api-design).\"\ntags: [error-handling, resilience, retry, circuit-breaker, error-boundary, typed-errors, fault-tolerance]\nrecommends: [debug, observability, monitoring, api-design, secure-coding, testing-web, nextjs]\norigin: risco\n---\n\n# Error handling — classify, contain, surface\n\nYou are designing what happens *whenever anything in a class breaks*, not chasing\none crash (that is [`debug`](..\u002Fdebug\u002FSKILL.md)). Every failure gets classified,\ncontained, and surfaced — never swallowed. The deliverable, in that order: a typed\nerror taxonomy, a retry policy with caps and jitter, boundary placement, and a\ntwo-audience message contract — never a pile of `try { … } catch {}`.\n\n## Step 1 — Model failure as a taxonomy\n\nBucket every failure into one of three kinds. The bucket dictates the reaction;\nget the bucket wrong and every downstream decision is wrong too.\n\n| Bucket | Examples | Retry? | Tell the user | Tell the operator |\n|---|---|---|---|---|\n| **Domain \u002F expected** | insufficient funds, slot taken, validation failed | No | Yes, actionable | info — it is normal |\n| **Infrastructure \u002F transient** | timeout, 503, connection reset, 429 | Yes (capped) | \"temporary, retrying\" | warn — watch the rate |\n| **Programmer error \u002F bug** | null deref, bad assertion, type error | No | generic \"something broke\" + id | error — page if frequent |\n\n### Result vs throw\n\nDecide per call site, not per codebase:\n\n- **`Result\u003CT, E>`** for *expected domain* failures the caller must handle. The\n  type checker forces a branch — the failure cannot be ignored by accident.\n- **`throw`** for *exceptional \u002F programmer* errors. These should crash up to the\n  nearest boundary, not be threaded through every signature.\n\nIn TypeScript, `neverthrow` (current) is the instrument for the Result path:\n\n```ts\nimport { ok, err, Result } from \"neverthrow\";\n\ntype ChargeError = \"insufficient_funds\" | \"card_declined\";\n\n\u002F\u002F Expected domain failure → Result. The caller MUST handle both arms.\nfunction charge(cents: number, balance: number): Result\u003Cnumber, ChargeError> {\n  if (cents > balance) return err(\"insufficient_funds\");\n  return ok(balance - cents);\n}\n\nconst r = charge(500, 200);\nif (r.isErr()) {\n  \u002F\u002F r.error is the typed union — exhaustive, no `any`.\n}\n```\n\n### Stable codes and cause chaining\n\nEvery error carries a **stable `code`** (a string the UI and logs key off, never\nthe human message) and **never drops the original cause**.\n\n```ts\n\u002F\u002F BAD — string error, loses the original, nothing to branch on.\nthrow new Error(\"payment failed\");\n\n\u002F\u002F GOOD — typed class, stable code, cause preserved.\nclass PaymentError extends Error {\n  constructor(public code: \"provider_down\" | \"declined\", cause?: unknown) {\n    super(code);\n    this.name = \"PaymentError\";\n    this.cause = cause; \u002F\u002F the original error\u002Fstack survives for the log\n  }\n}\ntry {\n  await provider.charge();\n} catch (e) {\n  throw new PaymentError(\"provider_down\", e); \u002F\u002F wrap, do not erase\n}\n```\n\nCross-language error-class skeletons (Python, Java, Go, .NET) live in\n[`references\u002Fretry-and-resilience.md`](references\u002Fretry-and-resilience.md).\n\n## Step 2 — Decide retryability\n\nRetry **only** transient failures, and **only** on idempotent operations. Retrying\nthe wrong thing turns one slow dependency into a self-inflicted outage.\n\n| Retry these (transient) | Never retry these (permanent) |\n|---|---|\n| Network error, connection reset | 400 bad request, 422 unprocessable |\n| Timeout | 401 \u002F 403 (auth\u002Fpermission) |\n| 429 too many requests (honor `Retry-After`) | 404 not found |\n| 503 \u002F 502 \u002F 504 | Any business-rule rejection (insufficient funds) |\n| 500 **on a GET** (idempotent) | 500 on a non-idempotent POST without a key |\n\n**Idempotency is a precondition, not a nicety.** A retried POST that creates a\ncharge can double-charge. Retry only operations that are idempotent by nature\n(GET, PUT, DELETE) or that carry an **idempotency key** so the server dedupes.\nKey design itself belongs to [`..\u002Fapi-design\u002FSKILL.md`](..\u002Fapi-design\u002FSKILL.md);\nhere you just require one before you retry a mutation.\n\n**Caps (industry-converged — AWS Builders' Library, REL05-BP03):**\n\n- Max **3–5** total attempts.\n- Base delay **100–200ms**, doubling per attempt.\n- Per-delay cap **10–30s**; total retry budget **10–60s** then give up.\n- **Full jitter** to spread load — beats fixed and equal jitter:\n\n```text\ndelay = random_between(0, min(cap, base * 2 ** attempt))\n```\n\nSet a **per-attempt timeout first**, then retry — a retry on a call that never\ntimes out just stacks hung requests.\n\n```ts\n\u002F\u002F GOOD — classify before retrying; cap; full jitter; per-attempt timeout.\nasync function withRetry\u003CT>(fn: () => Promise\u003CT>, max = 4): Promise\u003CT> {\n  for (let attempt = 0; ; attempt++) {\n    try {\n      return await fn(); \u002F\u002F fn must enforce its own per-attempt timeout\n    } catch (e) {\n      if (!isTransient(e) || attempt >= max - 1) throw e; \u002F\u002F permanent or budget spent\n      const cap = 10_000, base = 150;\n      const delay = Math.random() * Math.min(cap, base * 2 ** attempt); \u002F\u002F full jitter\n      await new Promise((r) => setTimeout(r, delay));\n    }\n  }\n}\n```\n\nPer-language `withRetry` (Python `tenacity`, Java Resilience4j, .NET Polly) is in\n[`references\u002Fretry-and-resilience.md`](references\u002Fretry-and-resilience.md).\n\n## Step 3 — Contain blast radius\n\nRetries alone make a struggling dependency worse. Contain it.\n\n- **Timeout every outbound call.** No timeout is a bug, not a default. An\n  un-timed call holds a connection until the OS gives up — minutes you do not have.\n- **Circuit breaker** — stop hammering a dead dependency. Three states:\n  - **Closed**: requests flow; count failures.\n  - **Open**: trip at ~**50% failure** over a ~**20-request** window; reject fast\n    for **30–60s** without calling downstream.\n  - **Half-Open**: after the cooldown, let a probe through; success → Closed,\n    failure → Open again.\n  - Critical services trip tighter (~30%); tolerant ones up to ~70%.\n- **Instruments (current):** Opossum (Node — defaults timeout 3000ms \u002F\n  errorThresholdPercentage 50 \u002F resetTimeout 30000ms), Polly 8.6.6 (.NET fluent\n  pipelines), Resilience4j 2.3.0 (Java 17+ `2.x` line; a `3.x` line targets Java\n  21). The config matrix is in\n  [`references\u002Fretry-and-resilience.md`](references\u002Fretry-and-resilience.md).\n- **Fallback \u002F graceful degradation** — when the breaker is Open, serve a stale\n  cache, a safe default, or an honest \"this feature is temporarily unavailable\".\n  Degrade; do not 500 the whole page.\n- **Bulkhead** — isolate resource pools (separate connection pool \u002F worker queue\n  per dependency) so one saturated downstream cannot starve the rest. Sizing in\n  the reference.\n\n## Step 4 — Boundaries\n\nA boundary is where an unhandled failure is *caught and converted* into a\ncontained reaction. Place one at each level that can fail independently.\n\n### React \u002F Next.js App Router\n\n- **`error.tsx`** is a **route-segment** boundary. It MUST be a Client Component\n  (`'use client'`) and receives `{ error, reset }`. An error in a segment bubbles\n  to the nearest *parent* `error.tsx`.\n- **`error.tsx` does NOT catch an error thrown in its own segment's `layout.tsx`\n  or `template.tsx`.** Those run *outside* the boundary — move the boundary to the\n  parent segment to cover them.\n- **`global-error.tsx`** wraps the whole app and must render its own `\u003Chtml>` and\n  `\u003Cbody>` (it replaces the root layout when the root itself fails).\n- **Boundaries only catch errors during *render*.** Errors in event handlers,\n  `async` callbacks, `setTimeout`, or server-side data fetching are invisible to\n  them — handle those with explicit `try\u002Fcatch` + state.\n\n```tsx\n\"use client\"; \u002F\u002F app\u002Fdashboard\u002Ferror.tsx — REQUIRED\n\nexport default function Error({\n  error,\n  reset,\n}: {\n  error: Error & { digest?: string };\n  reset: () => void;\n}) {\n  \u002F\u002F Log to your telemetry sink (see observability); show the user the digest id.\n  return (\n    \u003Cdiv role=\"alert\">\n      \u003Cp>Something went wrong. Quote id {error.digest} to support.\u003C\u002Fp>\n      \u003Cbutton onClick={reset}>Try again\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\nThe full segment-tree placement map and the `global-error.tsx` skeleton are in\n[`references\u002Fboundaries-and-messaging.md`](references\u002Fboundaries-and-messaging.md).\nFramework specifics: [`..\u002Fnextjs\u002FSKILL.md`](..\u002Fnextjs\u002FSKILL.md).\n\n### Server and process\n\n- **Request boundary** — one error handler \u002F middleware that maps the taxonomy →\n  HTTP status, attaches a correlation id, and emits the operator log. Every route\n  funnels through it instead of formatting errors ad hoc.\n- **Process boundary** — a top-level `unhandledRejection` \u002F `uncaughtException`\n  handler (Node) or equivalent. Log the cause chain, then **exit and let the\n  supervisor restart**. A process that keeps running after an unhandled error is\n  running corrupted.\n\n## Step 5 — Surface it\n\nTwo audiences. Never conflate them — that is how stack traces reach end users and\nhow logs become useless.\n\n| | User message | Operator log |\n|---|---|---|\n| **Goal** | tell them what to do next | let you reconstruct what happened |\n| **Content** | plain language, one action, a correlation id | code, cause chain, request context, structured fields |\n| **Never** | stack trace, SQL, internal hostnames, PII | a swallowed\u002Flost cause |\n\n**Taxonomy → HTTP status** (the in-process map; the *wire envelope* shape —\nRFC 9457 problem+json — belongs to [`..\u002Fapi-design\u002FSKILL.md`](..\u002Fapi-design\u002FSKILL.md);\n*shipping* the log to a sink belongs to [`..\u002Fobservability\u002FSKILL.md`](..\u002Fobservability\u002FSKILL.md)):\n\n| Bucket \u002F code | Status |\n|---|---|\n| validation \u002F bad input | 400 \u002F 422 |\n| unauthenticated \u002F forbidden | 401 \u002F 403 |\n| not found | 404 |\n| domain conflict (slot taken) | 409 |\n| transient downstream \u002F breaker open | 503 (+ `Retry-After`) |\n| programmer error \u002F unknown | 500 |\n\n```text\nBAD  → alert(\"TypeError: cannot read 'id' of undefined\")\nGOOD → \"We couldn't load your orders. Try again in a moment — id a1b2c3.\"\n\nBAD  → 500 { \"error\": \"ECONNREFUSED 10.0.3.12:5432\" }   \u002F\u002F leaks topology\nGOOD → 503 { \"code\": \"upstream_unavailable\", \"correlationId\": \"a1b2c3\" }\n```\n\nMore before\u002Fafter rewrites and the copy contract are in\n[`references\u002Fboundaries-and-messaging.md`](references\u002Fboundaries-and-messaging.md).\n\n## Anti-patterns\n\n| Anti-pattern | Why it bites | Fix |\n|---|---|---|\n| Empty `catch {}` \u002F `except: pass` | failure vanishes; you debug blind later | handle, or rethrow with context |\n| Bare `except:` (Python) | swallows `KeyboardInterrupt`\u002F`SystemExit` too | catch the specific type |\n| Retry everything, including 4xx | retrying a 400 just burns budget; never succeeds | retry only the transient table |\n| Retry a non-idempotent POST without a key | double-charges, duplicate rows | require an idempotency key first |\n| Infinite retry, no cap or jitter | thundering herd; turns a blip into an outage | cap attempts + full jitter + budget |\n| Leak stack trace \u002F SQL to the user | hands attackers your internals | generic message + id; detail to the log |\n| Expect `error.tsx` to catch its own segment's `layout` error | it runs outside the boundary; nothing catches it | move the boundary to the parent |\n| `alert(e.message)` as the handler | blocks the UI, leaks internals, no recovery | render an `error.tsx` with `reset` |\n| Catch-and-rethrow that drops `cause` | the root error is gone; logs are a dead end | wrap, set `cause`, preserve the chain |\n| Log the error **and** rethrow | double-logged at every layer; noise buries signal | log at the boundary, or rethrow — not both |\n| Swallow, then `return null` | callers deref null later, far from the cause | return a typed `Result` error |\n| Outbound call with no timeout | one hung dependency exhausts the pool | timeout every call, then retry |\n| One giant `try` around 200 lines | you cannot tell which call failed | scope `try` to the fallible call |\n| Treat every error as a retryable transient | masks real bugs as \"flaky\" | classify first (Step 1), then react |\n\n## The gate\n\nBefore claiming the failure path is handled, read your diff against the table\nabove — those rows *are* the checklist. `scripts\u002Fverify.sh \u003Cpath>` scans the\nworking tree for the highest-signal ones. It is **advisory** (exit 0 with\nwarnings); pass `--strict` to make any hit fail. It is heuristic — it flags,\nyou judge.\n","# Error handling — classify, contain, surface\n\nYou are designing what happens *whenever anything in a class breaks*, not chasing\none crash (that is [`debug`](..\u002Fdebug\u002FSKILL.md)). Every failure gets classified,\ncontained, and surfaced — never swallowed. The deliverable, in that order: a typed\nerror taxonomy, a retry policy with caps and jitter, boundary placement, and a\ntwo-audience message contract — never a pile of `try { … } catch {}`.\n\n## Step 1 — Model failure as a taxonomy\n\nBucket every failure into one of three kinds. The bucket dictates the reaction;\nget the bucket wrong and every downstream decision is wrong too.\n\n| Bucket | Examples | Retry? | Tell the user | Tell the operator |\n|---|---|---|---|---|\n| **Domain \u002F expected** | insufficient funds, slot taken, validation failed | No | Yes, actionable | info — it is normal |\n| **Infrastructure \u002F transient** | timeout, 503, connection reset, 429 | Yes (capped) | \"temporary, retrying\" | warn — watch the rate |\n| **Programmer error \u002F bug** | null deref, bad assertion, type error | No | generic \"something broke\" + id | error — page if frequent |\n\n### Result vs throw\n\nDecide per call site, not per codebase:\n\n- **`Result\u003CT, E>`** for *expected domain* failures the caller must handle. The\n  type checker forces a branch — the failure cannot be ignored by accident.\n- **`throw`** for *exceptional \u002F programmer* errors. These should crash up to the\n  nearest boundary, not be threaded through every signature.\n\nIn TypeScript, `neverthrow` (current) is the instrument for the Result path:\n\n```ts\nimport { ok, err, Result } from \"neverthrow\";\n\ntype ChargeError = \"insufficient_funds\" | \"card_declined\";\n\n\u002F\u002F Expected domain failure → Result. The caller MUST handle both arms.\nfunction charge(cents: number, balance: number): Result\u003Cnumber, ChargeError> {\n  if (cents > balance) return err(\"insufficient_funds\");\n  return ok(balance - cents);\n}\n\nconst r = charge(500, 200);\nif (r.isErr()) {\n  \u002F\u002F r.error is the typed union — exhaustive, no `any`.\n}\n```\n\n### Stable codes and cause chaining\n\nEvery error carries a **stable `code`** (a string the UI and logs key off, never\nthe human message) and **never drops the original cause**.\n\n```ts\n\u002F\u002F BAD — string error, loses the original, nothing to branch on.\nthrow new Error(\"payment failed\");\n\n\u002F\u002F GOOD — typed class, stable code, cause preserved.\nclass PaymentError extends Error {\n  constructor(public code: \"provider_down\" | \"declined\", cause?: unknown) {\n    super(code);\n    this.name = \"PaymentError\";\n    this.cause = cause; \u002F\u002F the original error\u002Fstack survives for the log\n  }\n}\ntry {\n  await provider.charge();\n} catch (e) {\n  throw new PaymentError(\"provider_down\", e); \u002F\u002F wrap, do not erase\n}\n```\n\nCross-language error-class skeletons (Python, Java, Go, .NET) live in\n[`references\u002Fretry-and-resilience.md`](references\u002Fretry-and-resilience.md).\n\n## Step 2 — Decide retryability\n\nRetry **only** transient failures, and **only** on idempotent operations. Retrying\nthe wrong thing turns one slow dependency into a self-inflicted outage.\n\n| Retry these (transient) | Never retry these (permanent) |\n|---|---|\n| Network error, connection reset | 400 bad request, 422 unprocessable |\n| Timeout | 401 \u002F 403 (auth\u002Fpermission) |\n| 429 too many requests (honor `Retry-After`) | 404 not found |\n| 503 \u002F 502 \u002F 504 | Any business-rule rejection (insufficient funds) |\n| 500 **on a GET** (idempotent) | 500 on a non-idempotent POST without a key |\n\n**Idempotency is a precondition, not a nicety.** A retried POST that creates a\ncharge can double-charge. Retry only operations that are idempotent by nature\n(GET, PUT, DELETE) or that carry an **idempotency key** so the server dedupes.\nKey design itself belongs to [`..\u002Fapi-design\u002FSKILL.md`](..\u002Fapi-design\u002FSKILL.md);\nhere you just require one before you retry a mutation.\n\n**Caps (industry-converged — AWS Builders' Library, REL05-BP03):**\n\n- Max **3–5** total attempts.\n- Base delay **100–200ms**, doubling per attempt.\n- Per-delay cap **10–30s**; total retry budget **10–60s** then give up.\n- **Full jitter** to spread load — beats fixed and equal jitter:\n\n```text\ndelay = random_between(0, min(cap, base * 2 ** attempt))\n```\n\nSet a **per-attempt timeout first**, then retry — a retry on a call that never\ntimes out just stacks hung requests.\n\n```ts\n\u002F\u002F GOOD — classify before retrying; cap; full jitter; per-attempt timeout.\nasync function withRetry\u003CT>(fn: () => Promise\u003CT>, max = 4): Promise\u003CT> {\n  for (let attempt = 0; ; attempt++) {\n    try {\n      return await fn(); \u002F\u002F fn must enforce its own per-attempt timeout\n    } catch (e) {\n      if (!isTransient(e) || attempt >= max - 1) throw e; \u002F\u002F permanent or budget spent\n      const cap = 10_000, base = 150;\n      const delay = Math.random() * Math.min(cap, base * 2 ** attempt); \u002F\u002F full jitter\n      await new Promise((r) => setTimeout(r, delay));\n    }\n  }\n}\n```\n\nPer-language `withRetry` (Python `tenacity`, Java Resilience4j, .NET Polly) is in\n[`references\u002Fretry-and-resilience.md`](references\u002Fretry-and-resilience.md).\n\n## Step 3 — Contain blast radius\n\nRetries alone make a struggling dependency worse. Contain it.\n\n- **Timeout every outbound call.** No timeout is a bug, not a default. An\n  un-timed call holds a connection until the OS gives up — minutes you do not have.\n- **Circuit breaker** — stop hammering a dead dependency. Three states:\n  - **Closed**: requests flow; count failures.\n  - **Open**: trip at ~**50% failure** over a ~**20-request** window; reject fast\n    for **30–60s** without calling downstream.\n  - **Half-Open**: after the cooldown, let a probe through; success → Closed,\n    failure → Open again.\n  - Critical services trip tighter (~30%); tolerant ones up to ~70%.\n- **Instruments (current):** Opossum (Node — defaults timeout 3000ms \u002F\n  errorThresholdPercentage 50 \u002F resetTimeout 30000ms), Polly 8.6.6 (.NET fluent\n  pipelines), Resilience4j 2.3.0 (Java 17+ `2.x` line; a `3.x` line targets Java\n  21). The config matrix is in\n  [`references\u002Fretry-and-resilience.md`](references\u002Fretry-and-resilience.md).\n- **Fallback \u002F graceful degradation** — when the breaker is Open, serve a stale\n  cache, a safe default, or an honest \"this feature is temporarily unavailable\".\n  Degrade; do not 500 the whole page.\n- **Bulkhead** — isolate resource pools (separate connection pool \u002F worker queue\n  per dependency) so one saturated downstream cannot starve the rest. Sizing in\n  the reference.\n\n## Step 4 — Boundaries\n\nA boundary is where an unhandled failure is *caught and converted* into a\ncontained reaction. Place one at each level that can fail independently.\n\n### React \u002F Next.js App Router\n\n- **`error.tsx`** is a **route-segment** boundary. It MUST be a Client Component\n  (`'use client'`) and receives `{ error, reset }`. An error in a segment bubbles\n  to the nearest *parent* `error.tsx`.\n- **`error.tsx` does NOT catch an error thrown in its own segment's `layout.tsx`\n  or `template.tsx`.** Those run *outside* the boundary — move the boundary to the\n  parent segment to cover them.\n- **`global-error.tsx`** wraps the whole app and must render its own `\u003Chtml>` and\n  `\u003Cbody>` (it replaces the root layout when the root itself fails).\n- **Boundaries only catch errors during *render*.** Errors in event handlers,\n  `async` callbacks, `setTimeout`, or server-side data fetching are invisible to\n  them — handle those with explicit `try\u002Fcatch` + state.\n\n```tsx\n\"use client\"; \u002F\u002F app\u002Fdashboard\u002Ferror.tsx — REQUIRED\n\nexport default function Error({\n  error,\n  reset,\n}: {\n  error: Error & { digest?: string };\n  reset: () => void;\n}) {\n  \u002F\u002F Log to your telemetry sink (see observability); show the user the digest id.\n  return (\n    \u003Cdiv role=\"alert\">\n      \u003Cp>Something went wrong. Quote id {error.digest} to support.\u003C\u002Fp>\n      \u003Cbutton onClick={reset}>Try again\u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  );\n}\n```\n\nThe full segment-tree placement map and the `global-error.tsx` skeleton are in\n[`references\u002Fboundaries-and-messaging.md`](references\u002Fboundaries-and-messaging.md).\nFramework specifics: [`..\u002Fnextjs\u002FSKILL.md`](..\u002Fnextjs\u002FSKILL.md).\n\n### Server and process\n\n- **Request boundary** — one error handler \u002F middleware that maps the taxonomy →\n  HTTP status, attaches a correlation id, and emits the operator log. Every route\n  funnels through it instead of formatting errors ad hoc.\n- **Process boundary** — a top-level `unhandledRejection` \u002F `uncaughtException`\n  handler (Node) or equivalent. Log the cause chain, then **exit and let the\n  supervisor restart**. A process that keeps running after an unhandled error is\n  running corrupted.\n\n## Step 5 — Surface it\n\nTwo audiences. Never conflate them — that is how stack traces reach end users and\nhow logs become useless.\n\n| | User message | Operator log |\n|---|---|---|\n| **Goal** | tell them what to do next | let you reconstruct what happened |\n| **Content** | plain language, one action, a correlation id | code, cause chain, request context, structured fields |\n| **Never** | stack trace, SQL, internal hostnames, PII | a swallowed\u002Flost cause |\n\n**Taxonomy → HTTP status** (the in-process map; the *wire envelope* shape —\nRFC 9457 problem+json — belongs to [`..\u002Fapi-design\u002FSKILL.md`](..\u002Fapi-design\u002FSKILL.md);\n*shipping* the log to a sink belongs to [`..\u002Fobservability\u002FSKILL.md`](..\u002Fobservability\u002FSKILL.md)):\n\n| Bucket \u002F code | Status |\n|---|---|\n| validation \u002F bad input | 400 \u002F 422 |\n| unauthenticated \u002F forbidden | 401 \u002F 403 |\n| not found | 404 |\n| domain conflict (slot taken) | 409 |\n| transient downstream \u002F breaker open | 503 (+ `Retry-After`) |\n| programmer error \u002F unknown | 500 |\n\n```text\nBAD  → alert(\"TypeError: cannot read 'id' of undefined\")\nGOOD → \"We couldn't load your orders. Try again in a moment — id a1b2c3.\"\n\nBAD  → 500 { \"error\": \"ECONNREFUSED 10.0.3.12:5432\" }   \u002F\u002F leaks topology\nGOOD → 503 { \"code\": \"upstream_unavailable\", \"correlationId\": \"a1b2c3\" }\n```\n\nMore before\u002Fafter rewrites and the copy contract are in\n[`references\u002Fboundaries-and-messaging.md`](references\u002Fboundaries-and-messaging.md).\n\n## Anti-patterns\n\n| Anti-pattern | Why it bites | Fix |\n|---|---|---|\n| Empty `catch {}` \u002F `except: pass` | failure vanishes; you debug blind later | handle, or rethrow with context |\n| Bare `except:` (Python) | swallows `KeyboardInterrupt`\u002F`SystemExit` too | catch the specific type |\n| Retry everything, including 4xx | retrying a 400 just burns budget; never succeeds | retry only the transient table |\n| Retry a non-idempotent POST without a key | double-charges, duplicate rows | require an idempotency key first |\n| Infinite retry, no cap or jitter | thundering herd; turns a blip into an outage | cap attempts + full jitter + budget |\n| Leak stack trace \u002F SQL to the user | hands attackers your internals | generic message + id; detail to the log |\n| Expect `error.tsx` to catch its own segment's `layout` error | it runs outside the boundary; nothing catches it | move the boundary to the parent |\n| `alert(e.message)` as the handler | blocks the UI, leaks internals, no recovery | render an `error.tsx` with `reset` |\n| Catch-and-rethrow that drops `cause` | the root error is gone; logs are a dead end | wrap, set `cause`, preserve the chain |\n| Log the error **and** rethrow | double-logged at every layer; noise buries signal | log at the boundary, or rethrow — not both |\n| Swallow, then `return null` | callers deref null later, far from the cause | return a typed `Result` error |\n| Outbound call with no timeout | one hung dependency exhausts the pool | timeout every call, then retry |\n| One giant `try` around 200 lines | you cannot tell which call failed | scope `try` to the fallible call |\n| Treat every error as a retryable transient | masks real bugs as \"flaky\" | classify first (Step 1), then react |\n\n## The gate\n\nBefore claiming the failure path is handled, read your diff against the table\nabove — those rows *are* the checklist. `scripts\u002Fverify.sh \u003Cpath>` scans the\nworking tree for the highest-signal ones. It is **advisory** (exit 0 with\nwarnings); pass `--strict` to make any hit fail. It is heuristic — it flags,\nyou judge.\n",{"name":5,"tags":24,"origin":31,"recommends":32,"description":7},[5,25,26,27,28,29,30],"resilience","retry","circuit-breaker","error-boundary","typed-errors","fault-tolerance","risco",[33,34,35,36,37,38,39],"debug","observability","monitoring","api-design","secure-coding","testing-web","nextjs","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","06-前端与设计\u002Ferror-handling",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill error-handling",{"tool":54,"command":55},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill error-handling",{"tool":57,"command":58},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill error-handling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Ferror-handling\u002FSKILL.md",true,[62,68,72,76],{"path":63,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":66,"sourceHtmlUrl":67},"evals\u002Fcases.yaml","REFERENCE","参考文档",4375,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Ferror-handling\u002Fevals\u002Fcases.yaml",{"path":69,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":70,"sourceHtmlUrl":71},"evals\u002FREADME.md",820,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Ferror-handling\u002Fevals\u002FREADME.md",{"path":73,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":74,"sourceHtmlUrl":75},"references\u002Fboundaries-and-messaging.md",4883,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Ferror-handling\u002Freferences\u002Fboundaries-and-messaging.md",{"path":77,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":78,"sourceHtmlUrl":79},"references\u002Fretry-and-resilience.md",5297,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F06-前端与设计\u002Ferror-handling\u002Freferences\u002Fretry-and-resilience.md",[81,88,93,100,107,114],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],{"skillNo":89,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":19},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":19},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]