Join errors and traverse error trees
Join errors and traverse error trees
When several operations fail independently, errors.Join (Go 1.20+) combines their non-nil errors into one error. The result wraps its children, so errors.Is and errors.As can find matches within them. If all arguments are nil, Join returns nil.
package main
import ( "errors" "fmt")
var ErrRead = errors.New("read failed")var ErrClose = errors.New("close failed")
func main() { err := errors.Join(ErrRead, nil, ErrClose) fmt.Println(err) fmt.Println(errors.Is(err, ErrRead), errors.Is(err, ErrClose)) fmt.Println(errors.Join(nil, nil) == nil)}Join skips nil arguments and separates the messages with newlines. Both failure identities remain visible. errors.Unwrap only calls Unwrap() error, not Unwrap() []error, so it returns nil for a joined error.
Expected output:
read failedclose failedtrue truetrueFind the first matching child
package main
import ( "errors" "fmt")
type StageError struct{ Stage string }
func (e StageError) Error() string { return e.Stage }func main() { err := errors.Join(fmt.Errorf("job: %w", StageError{"read"}), StageError{"write"}) var e StageError if errors.As(err, &e) { fmt.Println(e.Stage) } fmt.Println(errors.Unwrap(err) == nil)}Is and As inspect the root first, then each child subtree in order (depth-first). As returns the first matching error, not every match. Keep custom unwrap relationships finite and acyclic. Use Join to preserve independent failures rather than to invent additional errors.
Expected output:
readtrueTry it locally
Join sentinel errors ErrSave and ErrFlush with a nil argument. Print the Is checks for both and whether joining only nil returns nil.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Errors and cleanup 05: Join errors and traverse error trees
Check the lesson objective before moving on.
What does errors.Join(nil,nil) return?
How many matching errors does As extract per call?