error-handling-patterns
Skill9 starsChanged 5 months agoApache-2.0View on GitHub
How to handle errors explicitly and consistently across an app — validate at boundaries, classify operational vs programmer errors, add context while propagating, retry transient failures with backoff, and never swallow. Covers JS/Python/Go/Rust patterns with runnable checks.
16 other projects use a version of this.
Adopted by
Most recently taken up by
- enes9103/my-claude-agents-skillstheir own version, first seen Sep 28, 2026
- The-AIOS/aiostheir own version, first seen Sep 24, 2026
- anthuanvasquez/agents-skillstheir own version, first seen Sep 4, 2026
- TheHiddenDeveloper/jarvis-skillstheir own version, first seen Aug 19, 2026
- KhaledSaeed18/dotclaudetheir own version, first seen Jul 4, 2026
- JayRHa/AgentSkillstheir own version, first seen Jun 9, 2026
Used with
Projects with it also use python-project-structure and git-commit.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
Aver005Skillpython-project-structure
Python project organization, module architecture, and public API design. Use when setting up new projects, organizing modules, defining public interfaces with __all__, or planning directory layouts.
Also in 3 projects that use this
GitHubSkillgit-commit
Execute git commit with conventional commit message analysis, intelligent staging, and message generation. Use when user asks to commit changes, create a git commit, or mentions "/commit". Supports: (1) Auto-detecting type and scope from changes, (2) Generating conventional commit messages from diff, (3) Interactive commit with optional type/scope/description overrides, (4) Intelligent file staging for logical grouping
Also in 3 projects that use this
Other versions16 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 16
- The-AIOS/aios★ 69same name
- farming-labs/fm-skills★ 35same name
- autohandai/community-skills★ 11same name
- JayRHa/AgentSkills★ 11same name
- xfstudio/skills★ 9same name
- Vimalk0703/shipworthy★ 6same name
- KhaledSaeed18/dotclaude★ 5same name
- ai4brands-design/claude-skills★ 2same name
- anthuanvasquez/agents-skills★ 2same name
- CodeWithBehnam/cc-docs★ 2same name
6 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository16 other files it gives its agents.
- api-paginationSkill
- caching-strategiesSkill
- conventional-commitsSkill
- database-migrationsSkill
- git-collaboration-workflowsSkill
- owasp-top10Skill
- prompt-engineeringSkill
- readme-writingSkill
- refactoring-patternsSkill
- rest-api-designSkill
- secrets-managementSkill
- secure-authSkill
- sql-index-tuningSkill
- test-plan-designSkill
- vanara-orchestrateSkill
- vanara-routeSkill
The file
We split this skill into the rules it gives an agent
4 rules. 0 are common, 1 is distinctive, and 3 are very specific to this project.
0
Common
Most of the 15 edited versions we read keep these.
1
Distinctive
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 17
Every error sits on two axes that decide what you do with it:
- Very specific: line 39
Run scripts/lint-empty-catch.mjs in CI to catch these automatically.
- Very specific: line 74
Only operational, transient, idempotent failures are safe to retry — a 503 or a connection reset, not a 400 or a NullPointerException.
- Very specific: line 95
When NOT to retry, circuit breakers, and budgets are covered in references/retry-and-backoff.md.
“Common” is measured: kept by at least 6 in 10 of the 15 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Error Handling Patterns
Errors are part of the contract, not an afterthought. A robust system handles errors where it can act,
propagates them where it can't, and never lets a failure vanish silently. This skill is the deep
reference: the decisions, the trade-offs, and the anti-patterns. Heavy detail lives in references/,
copy-paste material in examples/, and a runnable linter for swallowed errors in scripts/.
Mental model
Every error sits on two axes that decide what you do with it:
| Axis | Question | Consequence |
| Operational vs programmer | Is this an expected runtime condition (network down, bad input) or a bug (null deref, broken invariant)? | Operational → recover/retry/surface. Programmer → fail fast, let it crash, fix the code. |
| Recoverable vs fatal | Can the caller do something useful about it here? | Yes → handle locally. No → add context and propagate. |
Classifying wrong is the root cause of most bad error handling: retrying a programmer bug forever, or
crashing the process over a single bad HTTP request. The full taxonomy is in
references/error-taxonomy.md.
The five rules
- Validate at the boundary. Reject bad input early with a clear, specific message (fail fast). Never trust data crossing a trust boundary — HTTP bodies, env vars, file contents, API responses.
- Classify the error. Operational errors are values you handle; programmer errors are bugs you
surface loudly. Don't
catchaTypeErrorto "be safe". - Add context as you propagate. Wrap with what you were doing and preserve the original cause and
stack (
new Error(msg, { cause })in JS,fmt.Errorf("...: %w", err)in Go). - One owner for user-facing messaging. Translate to a friendly message at the edge (the HTTP layer, the UI). Keep full detail in server-side logs only — never leak stack traces to users.
- Never swallow. An empty
catch {}, a bareexcept: pass, or a.catch(() => {})is a defect. Runscripts/lint-empty-catch.mjsin CI to catch these automatically.
Adding context without losing the cause
The single most valuable habit: wrap errors with context while chaining the original, so the final log shows the full causal trail from the low-level failure up to the request that triggered it.
// Node 16.9+ supports the standard `cause` option on Error.
async function placeOrder(userId, cart) {
try {
const order = await db.orders.insert({ userId, items: cart.items });
return order;
} catch (err) {
// Wrap: keep the DB error as `cause`, add the business context.
throw new Error(`failed to place order for user ${userId}`, { cause: err });
}
}# Python's `raise ... from` preserves the chain (shown as "The above exception
# was the direct cause of the following exception" in the traceback).
def place_order(user_id, cart):
try:
return db.orders.insert(user_id=user_id, items=cart.items)
except DBError as err:
raise OrderError(f"failed to place order for user {user_id}") from errLanguage-by-language patterns (try/catch vs Result/Either vs panics) are in
references/language-patterns.md.
Retrying transient failures
Only operational, transient, idempotent failures are safe to retry — a 503 or a connection reset,
not a 400 or a NullPointerException. Retry with exponential backoff plus full jitter to avoid
synchronized retry storms (the "thundering herd"), and always cap attempts and total time.
async function withRetry(fn, { retries = 4, baseMs = 100, isRetryable } = {}) {
let attempt = 0;
for (;;) {
try {
return await fn();
} catch (err) {
attempt++;
if (attempt > retries || (isRetryable && !isRetryable(err))) throw err;
const backoff = baseMs * 2 ** (attempt - 1);
const jittered = Math.random() * backoff; // full jitter
await new Promise((r) => setTimeout(r, jittered));
}
}
}When NOT to retry, circuit breakers, and budgets are covered in
references/retry-and-backoff.md.
Common pitfalls (anti-patterns)
- Swallowing errors — empty
catch {},except: pass,.catch(() => {}), orif err != nil {}in Go. The failure disappears and you debug blind. This is the #1 defect; lint for it. - Catch-log-rethrow-wrapped duplication — logging and rethrowing at every layer produces the same error logged ten times. Log once, at the boundary that owns the response.
- Catching too broadly —
except Exceptionorcatch (e)that also eatsKeyboardInterrupt, programmer bugs, orOutOfMemory. Catch the narrowest type you can actually handle. - Returning a sentinel instead of erroring — returning
null/-1/{}on failure forces every caller to remember the magic check; most won't. Prefer throwing or aResulttype. - Leaking internals to users — returning raw stack traces or SQL errors is both bad UX and a security leak (reveals schema, file paths, library versions).
- Retrying non-idempotent or non-transient operations — retrying a
POST /chargeon timeout can double-charge; retrying a400just wastes time. See the retry reference. - Losing the original cause —
throw new Error("save failed")without{ cause }discards the stack that tells you why.
When NOT to use / trade-offs
- Don't catch programmer errors to keep running. A bug that corrupted state should crash the process (let a supervisor like systemd/k8s/PM2 restart it clean) rather than limp along with bad data.
- Don't add a
Result/Eithertype to a small script — the ceremony outweighs the benefit. Plain exceptions are fine when there's one boundary and one owner. - Don't retry by default. Retries amplify load during incidents and can mask a real outage; only retry classified-transient, idempotent calls, and always with a budget.
- Defensive
try/catcheverywhere is a smell, not safety. It scatters handling, hides bugs, and makes control flow unreadable. Handle at meaningful boundaries.
Files in this package
references/error-taxonomy.md— operational vs programmer errors, and how the distinction drives recoveryreferences/retry-and-backoff.md— when to retry, exponential backoff, jitter, circuit breakers, budgetsreferences/language-patterns.md— try/catch vsResult/Eithervs panics across JS, Python, Go, Rustexamples/express-error-middleware.js— a complete centralized error handler with anAppErrorclassexamples/result-pattern.ts— a typedResult<T, E>with helpers, no exceptions for expected failuresscripts/lint-empty-catch.mjs— runnable Node linter that flags swallowed errors; supports--selftest
Pairs with the code-reviewer agent, the silent-failure-hunter agent, the rest-api-design skill
(for the HTTP error envelope), and the owasp-top10 skill (for not leaking sensitive data in errors).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

