Return useful Go errors
Keep the original cause and give callers context they can act on.
Errors are values
Go functions commonly return a value and an error. Check the error before using the value. Add context about the operation and identifier, but avoid logging secrets. Wrap with %w when a caller may need errors.Is or errors.As.
Keep ownership clear
The layer that can make a recovery decision should handle the error. Lower layers should return it with context. Do not both log and return the same error at every layer, which creates noisy duplicate reports.
record, err := store.Find(ctx, id)
if err != nil {
return Record{}, fmt.Errorf("find record %s: %w", id, err)
}
Let callers branch on meaning
Use a sentinel error or typed error when callers need a specific recovery path, such as a missing record. Wrap it with operation context and use errors.Is or errors.As at the boundary. Comparing error strings is brittle because context may change. When a caller has no recovery action, return the wrapped error rather than inventing a default value.
Test both value and error
A table-driven test should include success, missing data, and a failing dependency. On error, ensure the returned value does not look like a valid result that callers might use accidentally. Assert errors.Is for the underlying cause where that behavior is part of the contract. Keep log emission at the request or worker boundary to avoid duplicate entries.
Check your understanding
What does `%w` preserve that `%v` does not?
Show explanation
It wraps the underlying error so callers can inspect it with errors.Is or errors.As.
You can read for free. Create an account to save your progress.
Next lesson: Design small interfaces and safe slices →Put this lesson into practice
A practice activity at this level in the same module.
Try: Filter a slice into a new backing arrayFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.