使用 samber/oops 为 Go 错误补充结构化上下文、错误码与堆栈信息。
编程
golang-error-handling
试用面向 Go 工程师的惯用错误处理实践,覆盖创建、包装、检查与结构化日志。
它能做什么
整理 15 条 Go 错误处理最佳实践:用 %w 包装错误链,通过 errors.Is、errors.As 以及 Go 1.26+ 的 errors.AsType 检查链式错误,用 errors.Join(Go 1.20+)合并独立错误,以及自定义类型、哨兵错误、panic/recover 的使用边界。明确"单次处理"原则——错误要么记录,要么向上抛出,不能两者同时做,避免在日志聚合器里产生重复事件。日志侧推荐 slog,要求保持稳定的低基数模板以便聚合查询;HTTP 层给出请求日志中间件的写法;在需要堆栈、多租户上下文或结构化属性的生产环境错误中引入 samber/oops。提供三种工作模式:编码、PR 审查、代码库审计;审计模式可并行启动最多 5 个子代理,分别处理创建、包装、单次处理、panic/recover 与结构化日志五类问题。
什么时候用它
- 编写新的 Go 错误处理代码
- 审查 PR 中的错误处理改动
- 对存量代码库做错误处理审计
- 接入 slog 结构化错误日志以适配聚合工具
技能文档
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
相关技能
为 Go 服务接入五类可观测性信号的结构化指引,覆盖日志、指标、追踪、 profiling 与 RUM,并提供信号之间的关联方法。
为 Go 1.21+ 设计 samber/slog-* 日志流水线,按规范顺序组合采样、格式化、路由与多种后端 sink。
提供 Go 命名规范细则,涵盖包名、类型、错误、布尔、接收者、常量与测试。
Golang skills orchestrator — always active on any Golang coding, review, debug, or setup task. Reads the task context and loads the most relevant skills from samber/cc-skills-golang, often multiple at once: writing a gRPC service loads golang-grpc + golang-testing + golang-error-handling; debugging a panic loads golang-troubleshooting + golang-safety; auditing security loads golang-security + golang-lint + golang-safety. Also: disambiguates competing clusters when two skills seem to overlap (performance vs benchmark vs troubleshooting, samber/lo vs mo vs ro, DI cluster, safety vs security), and configures the project's agent-config file (CLAUDE.md, AGENTS.md, GEMINI.md, Cursor rules, or Copilot instructions) to force-trigger skills in a project (/golang-how-to configure).
在 Go 项目中使用 samber/mo 单子类型,用 Option、Result、Either 替代 nil 检查和 (T, error) 返回,构建可组合的类型安全流水线。