go-error-handling
Skill85 starsChanged 18 days agoMITView on GitHub
Go error handling patterns, wrapping, sentinel errors, custom error types, and the errors package. Grounded in Effective Go, Go Code Review Comments, and production-proven idioms. Use when implementing error handling, designing error types, debugging error chains, or reviewing error handling patterns. Trigger examples: "handle errors", "error wrapping", "custom error type", "sentinel errors", "errors.Is", "errors.As". Not for: panic/recover in middleware (go-api-design), test assertions (go-test-quality).
We split this skill into the rules it gives an agent
10 rules. 0 are common, 4 are distinctive, and 6 are very specific to this project.
0
Common
Most of the 3 edited versions we read keep these.
4
Distinctive
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 35
Read a reference file only when the summary below is not enough.
- Distinctive: line 39
When creating or returning an error, follow this tree:
- Very specific: line 49
Use package-level var for errors that callers need to check:
- Very specific: line 70
NEVER compare errors with ==.
- Distinctive: line 74
When errors need to carry structured information:
- Very specific: line 113
ALWAYS add context when propagating errors up the stack.
- Very specific: line 114
Use %w to preserve the error chain:
- Very specific: line 135
Use %v instead of %w when you explicitly want to break the error chain, preventing callers from depending on internal implementation errors:
- Distinctive: line 228
After writing or reviewing error handling, run the linters that prove the rules above (skip any that is not installed and note it):
- Very specific: line 240
Every fmt.Errorf wrapping uses %w (or %v with documented reason)
“Common” is measured: kept by at least 6 in 10 of the 3 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
Go Error Handling
Go's explicit error handling is a feature, not a limitation. These patterns ensure errors are informative, actionable, and properly propagated.
Community default. A project skill or agent-config rule that explicitly supersedes
go-error-handlingtakes precedence over this one.
Detailed reference material, loaded on demand:
references/patterns-and-boundaries.md— checking patterns,Ismethods, translating errors at the HTTP boundary, low-cardinality logging, the Go 1.27 vet check on%wwith pointer errors.
Read a reference file only when the summary below is not enough.
1. Error Decision Tree
When creating or returning an error, follow this tree:
- Simple, no extra context needed? →
errors.New("message") - Need to add context to existing error? →
fmt.Errorf("doing X: %w", err) - Caller needs to detect this error? → Sentinel
varor custom type - Error carries structured data? → Custom type implementing
error - Propagating from downstream? → Wrap with
%wand add context
2. Sentinel Errors
Use package-level var for errors that callers need to check:
// ✅ Good — exported sentinel error
var (
ErrNotFound = errors.New("user: not found")
ErrUnauthorized = errors.New("user: unauthorized")
)
// Naming convention: Err + Description
// Prefix with package context in the messageCallers check with errors.Is:
if errors.Is(err, user.ErrNotFound) {
// handle not found
}NEVER compare errors with ==. Always use errors.Is().
3. Custom Error Types
When errors need to carry structured information:
type ValidationError struct {
Field string
Message string
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("validation: field %s: %s", e.Field, e.Message)
}
// Callers extract it from the chain — Go 1.26+:
if valErr, ok := errors.AsType[*ValidationError](err); ok {
log.Printf("invalid field: %s", valErr.Field)
}
// Before Go 1.26:
var valErr *ValidationError
if errors.As(err, &valErr) {
log.Printf("invalid field: %s", valErr.Field)
}A custom type that wraps a cause must expose it, or errors.Is/errors.As
stop at your type and never see the error underneath:
type QueryError struct {
Query string
Err error
}
func (e *QueryError) Error() string { return "query " + e.Query + ": " + e.Err.Error() }
func (e *QueryError) Unwrap() error { return e.Err } // keeps the chain walkable4. Error Wrapping
ALWAYS add context when propagating errors up the stack.
Use %w to preserve the error chain:
// ✅ Good — context added, chain preserved
func getUser(id int64) (*User, error) {
row, err := db.QueryRow(ctx, query, id)
if err != nil {
return nil, fmt.Errorf("get user %d: %w", id, err)
}
// ...
}
// ❌ Bad — no context
return nil, err
// ❌ Bad — chain broken, callers can't errors.Is/As
return nil, fmt.Errorf("failed: %v", err)When NOT to use %w
Use %v instead of %w when you explicitly want to break the error chain,
preventing callers from depending on internal implementation errors:
// Intentionally hiding internal DB error from public API
return nil, fmt.Errorf("user lookup failed: %v", err)5. Handle Errors Exactly Once
An error should be either logged OR returned, never both:
// ✅ Good — return the error, let caller decide
func loadConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("load config %s: %w", path, err)
}
// ...
}
// ❌ Bad — log AND return (error handled twice)
func loadConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
log.Printf("failed to read config: %v", err) // handled once
return nil, err // handled again
}
// ...
}The rule: the component that decides what to do about the error is the one that logs/metrics it. Everyone else wraps and returns.
6. Error Naming Conventions
// Sentinel errors: Err prefix
var ErrNotFound = errors.New("not found")
// Error types: Error suffix
type NotFoundError struct { ... }
type ValidationError struct { ... }
// Error messages: lowercase, no punctuation, no "failed to" prefix
// Include context: "package: action: detail"
errors.New("auth: token expired")
fmt.Errorf("user: get by id %d: %w", id, err)7. Panic Rules
Panic is NOT error handling. Use panic only when:
- Program initialization fails and cannot continue (
template.Must, flag parsing) - Programmer error that should never happen (violated invariant)
- Nil dereference that indicates a bug, not a runtime condition
In tests, use t.Fatal / t.FailNow, never panic.
In HTTP handlers and middleware, recover from panics at the boundary to prevent one request from crashing the server.
8. Error Checking Patterns
- Scope the error to the
ifwhen nothing else needs it:if err := do(); err != nil { return fmt.Errorf("do: %w", err) }. - A deferred wrap on a named
errresult adds one prefix to every return path of a long function. - Collect independent failures (validation, parallel work) and return
errors.Join(errs...)—errors.Is/Assee every joined error.
9. Errors at Boundaries
- Publishing an error is a contract. Inside the module, wrap with
%w. At a boundary you publish (an exported library API, an RPC),%wmakes the wrapped error part of your API;%vor a new error keeps it private. - Translate before it reaches a user. Map domain errors to a status
and a stable message at the handler, and log the original once with its
chain.
err.Error()in a response leaks SQL, paths and hostnames. - Keep logged messages low-cardinality. The stable text is the message; IDs, paths and counts go in structured attributes so the log backend can group identical failures.
- Panics do not cross goroutines. A
recoveronly works in the goroutine that panicked — see go-concurrency-review. - Implement
Is(target error) boolon a type to leterrors.Ismatch a whole family of errors against one sentinel.
Examples for sections 8 and 9: references/patterns-and-boundaries.md.
Executable Verification
After writing or reviewing error handling, run the linters that prove the rules above (skip any that is not installed and note it):
go vet ./... # includes printf %w misuse
golangci-lint run --enable errcheck,errorlint # unchecked errors, %v-vs-%w,
# == comparisons on errorsVerification Checklist
- No
_discarding errors (unless explicitly justified with comment) - Every
fmt.Errorfwrapping uses%w(or%vwith documented reason) - Sentinel errors use
var Err...naming - Custom error types implement
errorinterface - Callers use
errors.Is/errors.As(errors.AsTypeon Go 1.26+), never==or type assertion - Custom types that wrap a cause implement
Unwrap() error - No log-and-return patterns
- Error messages are lowercase, contextual, chain-friendly
- No
err.Error()text in responses to users; logged messages are stable, details are attributes
Other versions3 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 3
- h0rn3t/golang-skills★ 7same name
- rjansen/skills★ 1same name
- narenaryan/agent-skills★ 0same name
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 repository38 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/go-skills.mdcCursor rule
- go-api-designSkill
- go-architecture-reviewSkill
- go-cliSkill
- go-dependency-injectionSkill
- go-design-patternsSkill
- go-graphqlSkill
- go-grpcSkill
- go-interface-designSkill
- go-openapiSkill
- go-project-layoutSkill
- go-code-reviewSkill
- go-coding-standardsSkill
- go-contextSkill
- go-data-structuresSkill
- go-documentationSkill
- go-modernizeSkill
- go-namingSkill
- go-databaseSkill
- go-concurrency-reviewSkill
- go-defensive-codingSkill
- go-observabilitySkill
- go-performance-reviewSkill
- go-security-auditSkill
- go-troubleshootingSkill
- go-test-qualitySkill
- go-test-table-drivenSkill
- git-commitSkill
- go-binary-sizeSkill
- go-build-releaseSkill
- go-ciSkill
- go-dependency-auditSkill
- go-refactoringSkill
- go-semantic-toolsSkill
- go-skills-routerSkill
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.

