error-handling-patterns
Skill5 starsChanged 5 months agoMITView on GitHub
Design and review error handling in a codebase: which errors are expected results versus bugs, typed error hierarchies or result types, where to catch (boundaries) and where never to, preserving cause chains, mapping errors to HTTP and CLI exit codes, retries with backoff for the transient, timeouts everywhere, and the logging that makes a failure diagnosable; with idioms for TypeScript, Python, Go, and Rust. Use when adding error handling to new code, when a codebase has inconsistent or swallowed errors, or when a failure in production was impossible to trace.
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
- vanara-agents/skillstheir own version, first seen Jul 14, 2026
- JayRHa/AgentSkillstheir own version, first seen Jun 9, 2026
Used with
Projects with it also use python-project-structure.
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
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
- vanara-agents/skills★ 9same name
- xfstudio/skills★ 9same name
- Vimalk0703/shipworthy★ 6same 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 repository89 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- site/llms-full.txtllms.txt
- site/llms.txtllms.txt
- improveSkill
- academic-writingSkill
- benchmark-reportingSkill
- bibtex-managerSkill
- citation-graphSkill
- citation-verifierSkill
- design-science-methodologySkill
- docx-thesisSkill
- experiment-reproducibilitySkill
- latex-toolkitSkill
- literature-searchSkill
- lit-review-synthesisSkill
- paper-readerSkill
- proofread-academicSkill
- research-figuresSkill
- research-methodologySkill
- research-questionSkill
- statistics-advisorSkill
- supervisor-updateSkill
- systematic-reviewSkill
- thesis-proposalSkill
- coolify-image-appSkill
- coolify-vps-baselineSkill
- deploy-verificationSkill
- express-prisma-coolify-imageSkill
- ghcr-coolify-pipelineSkill
- live-domain-cutoverSkill
- nextjs-coolify-imageSkill
- proxy-client-addressSkill
- vps-ops-toolkitSkill
- adr-writingSkill
- openapi-specSkill
- readme-writingSkill
- technical-writingSkill
- adversarial-reviewerSkill
- api-design-reviewSkill
- code-review-responseSkill
- create-agentSkill
- create-commandSkill
- create-hookSkill
- create-skillSkill
- db-migration-safetySkill
- dependency-upgradeSkill
- dockerfile-best-practicesSkill
- executing-plansSkill
- explain-codebaseSkill
- fix-ciSkill
- github-actions-pipelineSkill
- grill-with-docsSkill
- incident-postmortemSkill
- logging-and-observabilitySkill
- parallel-agentsSkill
- performance-optimizationSkill
- refactoring-recipesSkill
- solid-principlesSkill
- systematic-debuggingSkill
- test-driven-developmentSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
2 rules. 0 are common, 2 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 15 edited versions we read keep these.
2
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 28
Never: empty catch, catch-and-log-and-continue in the middle of a flow, catch of a broad type when a narrow one was meant, catch to return …
- Distinctive: line 33
Never convert an error to a string before it reaches the logger.
“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 has one purpose: when something goes wrong, the right party finds out, with enough context to act, and the system stays in a known state. Every pattern below is judged by that.
First decision: expected outcome or bug?
- Expected outcomes (not found, validation failed, permission denied, rate limited, conflict) are part of the function's contract. Represent them in the type: a result type, a discriminated union, a documented typed error. Callers handle them.
- Bugs and infrastructure failures (null where impossible, invariant broken, database down, out of memory) are exceptions. They propagate to a boundary that logs them and fails the operation; code in between does not catch them.
Mixing the two (throwing for "not found", or returning null for "database down") produces both noisy logs and silent failures.
Represent errors with types
- Base error class per domain (
AppErrorwithcode,httpStatus,isOperational), subclasses for categories (NotFoundError,ValidationError,ConflictError,UpstreamError). One place maps code to status and to user message. - Or a result type (
Result<T, E>/Either) for expected outcomes in functional codebases; then errors are values, exhaustively matched, and never forgotten. Do not use both styles in one module. - Errors carry structured context: the ids involved, the operation, the upstream status. Not the user's secrets, not whole request bodies.
Where to catch
Catch at boundaries: the HTTP handler, the CLI entry, the job runner, the message consumer, the top of a background task. There, translate to the boundary's vocabulary (status code, exit code, ack/nack), log once with full context, and stop.
In between, catch only to add context and rethrow (throw new UpstreamError("payments: charge failed", { cause: err, orderId })) or to handle an expected outcome you can actually resolve (retry, fallback with a documented consequence, default that is semantically correct).
Never: empty catch, catch-and-log-and-continue in the middle of a flow, catch of a broad type when a narrow one was meant, catch to return a sentinel that callers do not check.
Preserve the chain
new Error(msg, { cause })in JS;raise ... from errin Python;fmt.Errorf("...: %w", err)in Go;#[source]/thiserrorin Rust. The boundary logs the whole chain.- Never convert an error to a string before it reaches the logger; never replace it with a generic one.
Boundaries
HTTP: 400 validation, 401 unauthenticated, 403 forbidden, 404 not found, 409 conflict, 422 semantic, 429 rate limit, 500 unexpected (never leak the message), 502/503/504 upstream. One error response shape (RFC 9457 problem details). A 200 with { error } in the body is a bug.
CLI: exit 0 success, 1 general failure, 2 usage error, others per convention; message to stderr, machine output to stdout; --verbose for the chain.
Jobs and consumers: distinguish retryable (nack with delay, bounded attempts, then dead-letter with the error attached) from poison (dead-letter immediately). Idempotent handlers so retries are safe.
Background tasks and event handlers: an unhandled rejection in a fire-and-forget task must still reach the logger and the process's error metric; wrap the entry in a handler.
Transient failures
- Timeouts on every outbound call (HTTP, DB, queue), shorter than the caller's own timeout. A missing timeout is an error that presents as a hang.
- Retry only idempotent operations and only for transient classes (connection reset, 503, 429 with
Retry-After), with exponential backoff and jitter, a small maximum (3), and a total budget. Log each retry at debug, the final failure at error. - Circuit breaker when a dependency is failing at volume, so the system degrades instead of piling up timeouts.
- Fallbacks must be documented consequences: "serve cached price, flag stale" is a fallback; "return 0" is a silent failure.
Logging
Log once, at the boundary, at error level, with: the error class and message, the chain, the operation, the ids, the correlation/request id, and duration. Log expected outcomes (404, validation) at info or not at all; they are not incidents. Never log secrets, tokens, or full bodies. Count errors by class in a metric so a spike is visible.
Language idioms
- TypeScript:
catch (err: unknown)then narrow (err instanceof AppError);Promise.allSettledwhen partial failure is acceptable,Promise.allwhen one failure should fail all; no floating promises (awaitorvoidwith a handler);AbortSignal.timeout(ms)for fetch. - Python: catch specific exceptions, never bare
except:;raise ... from;contextlibfor cleanup;asyncio.timeout();logging.exception()at the boundary. - Go: return errors, wrap with
%w, check witherrors.Is/errors.As; sentinel errors for expected outcomes;context.WithTimeouton every call; never ignore a returned error (_ =needs a comment). - Rust:
Resulteverywhere,?to propagate,thiserrorfor library errors,anyhowat binaries;expectonly for invariants with a message that says why it cannot fail.
Review checklist
Every catch either rethrows with context, handles an expected outcome, or is at a boundary. No error is stringified early. Every outbound call has a timeout. Retries are bounded and idempotent. Boundaries return the right status. Logs at the boundary carry the chain and the ids. Tests cover each expected outcome and at least one unexpected failure path (test-gap-analyzer will check).
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.

