golang-error-handling
samber/cc-skills-golang
Idiomatic Go error handling: wrapping, inspection, structured logging, and production-grade error tracking.
What is golang-error-handling?
Comprehensive guide to Go error handling covering creation, wrapping with %w, errors.Is/As/Join, custom types, sentinel errors, panic/recover, the single handling rule, slog structured logging, and samber/oops for production errors. Use this when creating, wrapping, inspecting, or logging errors in Go code to ensure logs are usable at scale with log aggregation tools.
- Create and wrap errors with context using fmt.Errorf and %w verb
- Inspect error chains with errors.Is, errors.As, and errors.AsType (Go 1.26+)
- Combine independent errors with errors.Join (Go 1.20+)
- Define custom error types and sentinel errors for different error conditions
- Apply the single handling rule: log OR return errors, never both
- Use slog for structured error logging instead of fmt.Println or log.Printf
How to install golang-error-handling
npx skills add https://github.com/samber/cc-skills-golang --skill golang-error-handling- Go installed (go binary required)
- Familiarity with Go error interface and basic error handling
How to use golang-error-handling
- 1.Review the error handling best practices summary to understand the 15 core principles
- 2.Consult error creation reference when defining new errors or sentinel values
- 3.Use error wrapping and inspection reference when propagating or checking errors in code
- 4.Apply the single handling rule: decide whether to log or return each error, never both
- 5.Integrate slog for structured logging at error sites instead of unstructured print statements
- 6.For production errors needing stack traces, refer to samber/oops skill documentation
- 7.When auditing large codebases, use parallel sub-agents targeting creation, wrapping, single-handling rule, panic/recover, and structured logging categories
Use cases
- Writing new error handling code following best practices sequentially
- Reviewing PR diffs for error handling violations like swallowed errors or missing wrapping context
- Auditing existing codebases for error creation, wrapping, logging, and panic/recover patterns
- Integrating samber/oops for production errors requiring stack traces and structured attributes
- Setting up structured logging with slog for APM and log aggregation tools
- Go developers writing production code
- Reliability engineers reviewing error handling patterns
- Teams adopting structured logging and log aggregation
- Projects requiring audit trails and stack traces for errors
golang-error-handling FAQ
Use %w internally to preserve the error chain for errors.Is/As inspection. Use %v at system boundaries (e.g., HTTP responses) to control error chain exposure and prevent leaking internal details.
Sentinel errors are pre-allocated error values (like errors.New) matched with errors.Is for expected conditions. Custom error types carry rich context and data; use them when you need to attach structured information to an error.
Logging and returning the same error causes duplicate log entries that clutter log aggregators and make debugging harder. Choose one: either log the error and return nil, or return the error for the caller to handle.
Never use panic for expected error conditions. Reserve panic only for truly unrecoverable states (e.g., programmer bugs). For all expected failures, return errors and let the caller decide how to handle them.
Keep log message templates stable and attach high-cardinality data (IDs, paths, counts) as structured attributes. Avoid putting variable data directly into the message string used for grouping.
Full instructions (SKILL.md)
Source of truth, from samber/cc-skills-golang.
name: golang-error-handling
description: "Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See samber/cc-skills-golang@golang-samber-oops skill; for slog handler ecosystem → See samber/cc-skills-golang@golang-samber-slog skill."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents, and for projects using Golang.
metadata:
author: samber
version: "1.2.0"
openclaw:
emoji: "⚠"
homepage: https://github.com/samber/cc-skills-golang
requires:
bins:
- go
install: []
allowed-tools: Read Edit Write Glob Grep Bash(go:) Bash(golangci-lint:) Bash(git:*) Agent
Persona: You are a Go reliability engineer. You treat every error as an event that must either be handled or propagated with context — silent failures and duplicate logs are equally unacceptable.
Modes:
- Coding mode — writing new error handling code. Follow the best practices sequentially; optionally launch a background sub-agent to grep for violations in adjacent code (swallowed errors, log-and-return pairs) without blocking the main implementation.
- Review mode — reviewing a PR's error handling changes. Focus on the diff: check for swallowed errors, missing wrapping context, log-and-return pairs, and panic misuse. Sequential.
- Audit mode — auditing existing error handling across a codebase. Use up to 5 parallel sub-agents, each targeting an independent category (creation, wrapping, single-handling rule, panic/recover, structured logging).
Community default. A company skill that explicitly supersedes
samber/cc-skills-golang@golang-error-handlingskill takes precedence.
Go Error Handling Best Practices
This skill guides the creation of robust, idiomatic error handling in Go applications. Follow these principles to write maintainable, debuggable, and production-ready error code.
Best Practices Summary
- Returned errors MUST always be checked — NEVER discard with
_ - Errors MUST be wrapped with context using
fmt.Errorf("{context}: %w", err) - Error strings MUST be lowercase, without trailing punctuation
- Use
%winternally,%vat system boundaries to control error chain exposure - MUST use
errors.Isfor sentinel matching anderrors.As/errors.AsTypefor typed chain inspection instead of direct comparison or bare type assertions. For Go 1.26+, prefererrors.AsType[T](err)whenTimplementserror; useerrors.As(err, &target)for Go <1.26 or for non-error interface targets. - SHOULD use
errors.Join(Go 1.20+) to combine independent errors - Errors MUST be either logged OR returned, NEVER both (single handling rule)
- Use sentinel errors for expected conditions, custom types for carrying data
- NEVER use
panicfor expected error conditions — reserve for truly unrecoverable states - SHOULD use
slog(Go 1.21+) for structured error logging — notfmt.Printlnorlog.Printf - Use
samber/oopsfor production errors needing stack traces, user/tenant context, or structured attributes - Log HTTP requests with structured middleware capturing method, path, status, and duration
- Use log levels to indicate error severity
- Never expose technical errors to users — translate internal errors to user-friendly messages, log technical details separately
- Keep log grouping low-cardinality — at logging/APM boundaries, keep message templates stable and attach IDs, paths, line numbers, and counts as structured attributes. Error values may include useful operational context, but avoid putting high-cardinality data into the stable log message used for grouping.
Detailed Reference
-
Error Creation — How to create errors that tell the story: error messages should be lowercase, no punctuation, and describe what happened without prescribing action. Covers sentinel errors (one-time preallocation for performance), custom error types (for carrying rich context), and the decision table for which to use when.
-
Error Wrapping and Inspection — Why
fmt.Errorf("{context}: %w", err)beatsfmt.Errorf("{context}: %v", err)(chains vs concatenation). How to inspect chains witherrors.Is,errors.As, and Go 1.26+errors.AsTypefor type-safe error handling, anderrors.Joinfor combining independent errors. -
Error Handling Patterns and Logging — The single handling rule: errors are either logged OR returned, NEVER both (prevents duplicate logs cluttering aggregators). Panic/recover design,
samber/oopsfor production errors, andslogstructured logging integration for APM tools.
Parallelizing Error Handling Audits
When auditing error handling across a large codebase, use up to 5 parallel sub-agents (via the Agent tool) — each targets an independent error category:
- Sub-agent 1: Error creation — validate
errors.New/fmt.Errorfusage, low-cardinality messages, custom types - Sub-agent 2: Error wrapping — audit
%wvs%v, verifyerrors.Is/errors.Aspatterns - Sub-agent 3: Single handling rule — find log-and-return violations, swallowed errors, discarded errors (
_) - Sub-agent 4: Panic/recover — audit
panicusage, verify recovery at goroutine boundaries - Sub-agent 5: Structured logging — verify
slogusage at error sites, check for PII in error messages
Cross-References
- → See
samber/cc-skills-golang@golang-samber-oopsfor full samber/oops API, builder patterns, and logger integration - → See
samber/cc-skills-golang@golang-observabilityfor structured logging setup, log levels, and request logging middleware - → See
samber/cc-skills-golang@golang-safetyfor nil interface trap and nil error comparison pitfalls - → See
samber/cc-skills-golang@golang-namingfor error naming conventions (ErrNotFound, PathError) - → See
samber/cc-skills-golang@golang-continuous-integrationskill for automated AI-driven code review in CI using these guidelines
References
Related skills
More from samber/cc-skills-golang and the wider catalog.
golang-code-style
Go code style conventions for clarity, control flow, and readability—line breaking, variable declarations, and when comments help.
golang-performance
Go performance optimization patterns: identify bottlenecks with profiling, then apply the right fix.
golang-design-patterns
Idiomatic Go design patterns: functional options, constructors, error handling, resource lifecycle, graceful shutdown, and resilience.
golang-testing
Production-ready Go tests with table-driven patterns, testify integration, parallel execution, fuzzing, and leak detection.
golang-security
Security best practices and vulnerability prevention for Go code—injection, crypto, secrets, and authentication.
golang-concurrency
Go concurrency patterns: goroutines, channels, locks, and structured concurrency best practices.