golang-error-handling

作成者: samber

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`...

npx skills add https://github.com/samber/cc-skills-golang --skill golang-error-handling

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-handling skill 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

  1. Returned errors MUST always be checked — NEVER discard with _
  2. Errors MUST be wrapped with context using fmt.Errorf("{context}: %w", err)
  3. Error strings MUST be lowercase, without trailing punctuation
  4. Use %w internally, %v at system boundaries to control error chain exposure
  5. MUST use errors.Is for sentinel matching and errors.As/errors.AsType for typed chain inspection instead of direct comparison or bare type assertions. For Go 1.26+, prefer errors.AsType[T](err) when T implements error; use errors.As(err, &target) for Go <1.26 or for non-error interface targets.
  6. SHOULD use errors.Join (Go 1.20+) to combine independent errors
  7. Errors MUST be either logged OR returned, NEVER both (single handling rule)
  8. Use sentinel errors for expected conditions, custom types for carrying data
  9. NEVER use panic for expected error conditions — reserve for truly unrecoverable states
  10. SHOULD use slog (Go 1.21+) for structured error logging — not fmt.Println or log.Printf
  11. Use samber/oops for production errors needing stack traces, user/tenant context, or structured attributes
  12. Log HTTP requests with structured middleware capturing method, path, status, and duration
  13. Use log levels to indicate error severity
  14. Never expose technical errors to users — translate internal errors to user-friendly messages, log technical details separately
  15. 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) beats fmt.Errorf("{context}: %v", err) (chains vs concatenation). How to inspect chains with errors.Is, errors.As, and Go 1.26+ errors.AsType for type-safe error handling, and errors.Join for 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/oops for production errors, and slog structured 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.Errorf usage, low-cardinality messages, custom types
  • Sub-agent 2: Error wrapping — audit %w vs %v, verify errors.Is/errors.As patterns
  • Sub-agent 3: Single handling rule — find log-and-return violations, swallowed errors, discarded errors (_)
  • Sub-agent 4: Panic/recover — audit panic usage, verify recovery at goroutine boundaries
  • Sub-agent 5: Structured logging — verify slog usage at error sites, check for PII in error messages

Cross-References

  • → See samber/cc-skills-golang@golang-samber-oops for full samber/oops API, builder patterns, and logger integration
  • → See samber/cc-skills-golang@golang-observability for structured logging setup, log levels, and request logging middleware
  • → See samber/cc-skills-golang@golang-safety for nil interface trap and nil error comparison pitfalls
  • → See samber/cc-skills-golang@golang-naming for error naming conventions (ErrNotFound, PathError)
  • → See samber/cc-skills-golang@golang-continuous-integration skill for automated AI-driven code review in CI using these guidelines

References

samberのその他のスキル

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
慣用的なGo言語のデザインパターン — 関数型オプション、コンストラクタ、エラーフローとカスケード、リソース管理とライフサイクル、グレースフルシャットダウン、耐障害性、アーキテクチャ、依存性注入、データ処理、ストリーミングなど。アーキテクチャパターンを明示的に選択する際、関数型オプションを実装する際、コンストラクタAPIを設計する際、グレースフルシャットダウンを設定する際、耐障害性パターンを適用する際、または特定の問題に適合する慣用的なGoパターンを尋ねる際に適用します。
developmentdesigncode-review
golang-performance
samber
Golangのパフォーマンス最適化パターンと方法論 - XのボトルネックがあればYを適用。アロケーション削減、CPU効率、メモリレイアウト、GCチューニング、プーリング、キャッシング、ホットパス最適化をカバー。プロファイリングやベンチマークでボトルネックが特定され、それを修正するための適切な最適化パターンが必要な場合に使用。また、パフォーマンスコードレビューを行い、改善点や迅速なパフォーマンス向上を特定するのに役立つベンチマークを提案する場合にも使用。測定方法論には使用しない(→...)
developmentcode-review
golang-security
samber
Golangのセキュリティベストプラクティスと脆弱性防止。インジェクション(SQL、コマンド、XSS)、暗号化、ファイルシステムの安全性、ネットワークセキュリティ、クッキー、シークレット管理、メモリ安全性、ログ記録をカバー。Goコードのセキュリティに関する作成、レビュー、監査時、または暗号、I/O、シークレット管理、ユーザー入力処理、認証を含むリスクのあるコードに取り組む際に適用。セキュリティツールの設定を含む。
securitycode-reviewdevelopment
golang-database
samber
Goデータベースアクセスの包括的ガイド — パラメータ化クエリ、構造体スキャン、NULL許容カラム、トランザクション、分離レベル、SELECT FOR UPDATE、コネクションプール、バッチ処理、コンテキスト伝搬、マイグレーションツール。PostgreSQL、MariaDB、MySQL、SQLiteと連携するGolangコードの作成、レビュー、デバッグ時、データベーステスト時、またはdatabase/sql、sqlx、pgxに関する質問時に使用します。データベーススキーマやマイグレーションSQLは生成しません。
developmentdatabase
golang-lint
samber
GolangプロジェクトにおけるLintのベストプラクティスとgolangci-lintの設定 — リンターの実行、.golangci.ymlの設定、nolintディレクティブによる警告の抑制、Lint出力の解釈、リンターの選択。golangci-lintの設定時、Lint警告やnolint抑制について質問がある時、コード品質ツールのセットアップ時、またはリンターを選択する時に使用します。また、ユーザーがgolangci-lint、go vet、staticcheck、reviveに言及した場合にも使用します。
developmentcode-reviewtesting
golang-troubleshooting
samber
Troubleshoot Golang programs systematically - find and fix the root cause. Use when encountering bugs, crashes, deadlocks, or unexpected behavior in Go code. Covers debugging methodology, common Go pitfalls, test-driven debugging, pprof setup and capture, Delve debugger, race detection, GODEBUG tracing, and production debugging. Start here for any 'something is wrong' situation. Not for interpreting profiles or benchmarking (→ See `samber/cc-skills-golang@golang-benchmark` skill) or applying...
developmenttesting