Go core · 3 MIN READ
Read the failure path before the happy path
Trace a result and error through a complete boundary, including wrapping and partial results.
An error result is part of a function contract. The caller needs to know whether a value is valid when err is non-nil, who should add context, and which layer decides what the user sees. A short early return makes that contract visible.
Trace both returns
This function promises a useful positive integer only when its error is nil. Invalid syntax and a non-positive number are different failures. In each failure branch, return immediately; the normal result appears once at the bottom.
func positive(raw string) (int, error) {
n, err := strconv.Atoi(raw)
if err != nil {
return 0, fmt.Errorf("parse count: %w", err)
}
if n <= 0 {
return 0, errors.New("count must be positive")
}
return n, nil
}For "abc", Atoi fails and the first branch exits. For "0", parsing succeeds and validation fails. For "8", neither error branch runs and the caller receives 8, nil. No exception handler is needed to follow those paths.
Handle it at the boundary
The helper adds operation context without choosing an HTTP status or printing to a console. A CLI handler or HTTP adapter can decide how to report the error. Avoid logging the same error at every layer; repeated messages obscure a single failure.
Partial results need a documented contract
Some APIs deliberately return useful data with an error. io.Reader is a notable example: process the bytes returned before deciding what the error means. Do not generalize the early-return pattern into discarding all non-zero results. Read the particular API contract and distinguish expected absence, invalid input and infrastructure failure.
TAKE THIS WITH YOU
Follow each return as a pair. Handle errors deliberately, preserve a useful cause with wrapping, and use partial values only when the API promises them.
Check your understanding
Which statement is correct about a result with an error?
Go to the source
Progress stays in this browser. No account needed.