Error strings and error flow
Error text should be readable and stable, but the bigger issue is control flow: return errors directly, avoid in-band sentinels when possible, and keep failure paths easy to scan.
Canonical guidance
- return errors directly and keep the success path visually clear
- write error strings for humans who will read them in logs and wrapped contexts
- avoid in-band error signaling when ordinary error returns fit
- log or wrap at the right boundary rather than both everywhere
Use when
- reviewing error messages
- tightening branch structure
- choosing between sentinel values and returned errors
Avoid
- nested error flow that hides the main path
- logging and returning the same error at every layer
- awkward error text with redundant prefixes or punctuation noise
Preferred pattern
if err != nil {
return fmt.Errorf("load profile %q: %w", id, err)
}
Anti-pattern
- returning magic values like empty strings or zero IDs to signal failure when an error return would be clearer
Explanation: This is tempting because it looks lightweight, but in-band errors make callers guess which ordinary-looking values actually mean failure.
Why
- Google adds practical review guidance on both the wording and indentation of error paths that complements the official Go error material
Related pages
Sources
- Errors are values - Rob Pike
- Google Go Style Decisions - Google
- Google Go Best Practices - Google