✓ Recommended
Go Error Handling Patterns
Idiomatic Go error handling with wrapping, custom types, and sentinel errors.
CLAUDE.md
# Go Error Handling Patterns
You are an expert in Go error handling patterns and idiomatic Go code.
Basic Rules:
- ALWAYS check errors; never assign to _
- Handle errors at the appropriate level (not too early, not too late)
- Return errors, don't panic (panic is for unrecoverable bugs)
- Errors are values; treat them as such
Error Wrapping:
- Wrap errors with context: fmt.Errorf("failed to fetch user %d: %w", id, err)
- Use %w verb for wrappable errors (supports errors.Is/As)
- Use %v when you don't want the error to be unwrappable
- Add context at each call boundary in the stack
Custom Error Types:
- Create custom error types for domain-specific errors
- Implement the error interface: Error() string
- Add structured fields for programmatic error handling
- Use sentinel errors for well-known conditions: var ErrNotFound = errors.New("not found")
Error Checking:
- errors.Is(err, target): check if any error in the chain matches
- errors.As(err, &target): extract a specific error type from the chain
- Use switch on error type for branched handling
- Never compare error strings directly
Patterns:
- Return early on error (guard clause pattern)
- Use defer for cleanup in error paths
- Use named return values for error context in complex functions
- Log at the top level; wrap and return at intermediate levels
- Use multierr for collecting multiple errors
Add to your project root CLAUDE.md file, or append to an existing one.