Go: Keep multiple failures inspectable with errors.Join
When validation can report several independent failures at once, errors.Join keeps their identities available to callers. Use errors.Is to inspect the combined error.
Set up
Tested on Linux with Go 1.26.10. Use Bash with Go on your PATH. Keep the same terminal through cleanup, and stop if setup fails.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as errors_join_independent_failures.go:
package main
import (
"errors"
"fmt"
)
var errName = errors.New("name is required")
var errPort = errors.New("port is outside 1..65535")
func validate(name string, port int) error {
var problems []error
if name == "" {
problems = append(problems, errName)
}
if port < 1 || port > 65535 {
problems = append(problems, errPort)
}
return errors.Join(problems...)
}
func main() {
err := validate("", 70000)
fmt.Println("name failure:", errors.Is(err, errName))
fmt.Println("port failure:", errors.Is(err, errPort))
fmt.Println("single unwrap is nil:", errors.Unwrap(err) == nil)
fmt.Println("valid input:", validate("worker", 8080) == nil)
fmt.Println("all nil:", errors.Join(nil, nil) == nil)
}go run errors_join_independent_failures.goObserved output:
name failure: true
port failure: true
single unwrap is nil: true
valid input: true
all nil: trueRead the result
Both failures remain discoverable. An empty collection, or a collection containing only nil errors, produces nil. The single-error errors.Unwrap helper does not traverse a joined error, whose unwrap method returns a slice of errors; errors.Is understands that structure.
Apply it carefully
Joining errors does not run work concurrently or roll back earlier operations. Collect only failures that are meaningful together. Keep sentinel identity checks separate from human-readable messages, and avoid exposing internal error text directly in a public response.
See the Go standard-library reference.
Clean up
Remove the source and the empty scratch directory. Go may retain build-cache files outside this directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- errors_join_independent_failures.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.