samber/cc-skills-golang / skills/golang-error-handling
golang-error-handling
VerifiedIdiomatic 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.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 7.2 KB |
| evals/evals.json | config | 15.4 KB |
| references/error-creation.md | markdown | 5.6 KB |
| references/error-handling.md | markdown | 4.5 KB |
| references/error-wrapping.md | markdown | 3.8 KB |
references/error-wrapping.md
View on GitHub# Error Wrapping and Inspection
## Table of Contents
- [Error Wrapping with `%w`](#error-wrapping-with-w)
- [`%w` vs `%v`: controlling exposure](#w-vs-v-controlling-exposure)
- [Inspecting Errors: `errors.Is` and `errors.As`](#inspecting-errors-errorsis-and-errorsas)
- [`errors.Is` — match against a sentinel value](#errorsis--match-against-a-sentinel-value)
- [`errors.As / errors.AsType` — extract a typed error from the chain](#errorsas--errorsastype--extract-a-typed-error-from-the-chain)
- [Combining Errors with `errors.Join`](#combining-errors-with-errorsjoin)
- [Use case: validating multiple fields](#use-case-validating-multiple-fields)
- [Use case: parallel operations with independent failures](#use-case-parallel-operations-with-independent-failures)
- [`errors.Is` works through joined errors](#errorsis-works-through-joined-errors)
## Error Wrapping with `%w`
Wrapping preserves the original error in a chain that callers can inspect with `errors.Is` and `errors.As`. Errors SHOULD be wrapped at each layer to build a readable chain.
```go
// ✓ Good — wraps with context, preserves the chain
func (s *UserService) GetUser(id string) (*User, error) {
user, err := s.repo.FindByID(id)
if err != nil {
return nil, fmt.Errorf("getting user %s: %w", id, err)
}
return user, nil
}
```
### `%w` vs `%v`: controlling exposure
Use `%w` within your module to preserve the error chain. Use `%v` at public API / system boundaries to prevent callers from depending on internal error types.
```go
// Internal layer — wrap to preserve chain
func (r *repo) fetch(id string) error {
return fmt.Errorf("querying database: %w", err)
}
// Public API boundary — break chain to hide internals
func (s *PublicService) GetItem(id string) error {
err := s.repo.fetch(id)
if err != nil {
return fmt.Errorf("item unavailable: %v", err) // %v — callers cannot unwrap
}
return nil
}
```
## Inspecting Errors: `errors.Is` and `errors.As`
### `errors.Is` — match against a sentinel value
```go
// ✗ Bad — direct comparison breaks on wrapped errors
if err == sql.ErrNoRows {
// ✓ Good — traverses the entire error chain
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
```
### `errors.As / errors.AsType` — extract a typed error from the chain
```go
// ✗ Bad — type assertion breaks on wrapped errors
if ve, ok := err.(*ValidationError); ok {
// ✓ Good — traverses the entire error chain
var ve *ValidationError
if errors.As(err, &ve) {
log.Printf("validation failed on field %s: %s", ve.Field, ve.Msg)
}
// ✓ Better (Go 1.26+) — same behavior, simpler syntax
if ve, ok := errors.AsType[*ValidationError](err); ok {
log.Printf("validation failed on field %s: %s", ve.Field, ve.Msg)
}
```
## Combining Errors with `errors.Join`
`errors.Join` (Go 1.20+) combines multiple independent errors into one. The combined error works with `errors.Is` and `errors.As` — each inner error is inspectable.
### Use case: validating multiple fields
```go
func validateUser(u User) error {
var errs []error
if u.Name == "" {
errs = append(errs, errors.New("name is required"))
}
if u.Email == "" {
errs = append(errs, errors.New("email is required"))
}
return errors.Join(errs...) // returns nil if errs is empty
}
```
### Use case: parallel operations with independent failures
```go
func closeAll(closers ...io.Closer) error {
var errs []error
for _, c := range closers {
if err := c.Close(); err != nil {
errs = append(errs, err)
}
}
return errors.Join(errs...)
}
```
### `errors.Is` works through joined errors
```go
err := errors.Join(ErrNotFound, ErrUnauthorized)
errors.Is(err, ErrNotFound) // true
errors.Is(err, ErrUnauthorized) // true
```
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |