Inspect Multi-Error Trees With errors.Join And Unwrap
Build a nested multi-error tree with errors.Join and fmt.Errorf %w, then traverse both Unwrap() []error and Unwrap() error branches recursively.
Code
package main
import (
"errors"
"fmt"
)
var (
ErrConfig = errors.New("missing config")
ErrSecret = errors.New("empty secret")
)
func collectLeaves(err error, out *[]error) {
if err == nil {
return
}
switch x := err.(type) {
case interface{ Unwrap() []error }:
for _, child := range x.Unwrap() {
collectLeaves(child, out)
}
case interface{ Unwrap() error }:
collectLeaves(x.Unwrap(), out)
default:
*out = append(*out, err)
}
}
func main() {
ioGroup := errors.Join(ErrConfig, errors.New("port out of range"))
authGroup := fmt.Errorf("auth init: %w", errors.Join(ErrSecret, errors.New("expired cert")))
root := fmt.Errorf("startup failed: %w", errors.Join(ioGroup, authGroup))
var leaves []error
collectLeaves(root, &leaves)
fmt.Printf("leaf count: %d\n", len(leaves))
for i, leaf := range leaves {
fmt.Printf(" leaf[%d]: %v\n", i, leaf)
}
fmt.Println("contains ErrConfig:", errors.Is(root, ErrConfig))
fmt.Println("contains ErrSecret:", errors.Is(root, ErrSecret))
}Logic trace — Inspect Multi-Error Trees With errors.Join And Unwrap
Execution flow resides solely inside the helpers collectLeaves and main.
The loop for _, child := range x.Unwrap() is the only repeated construct.
Caveats
- Install steps are not needed since standard library modules handle everything.
Applying it
The entry-point signature is func collectLeaves(err error, out *[]error)
The run emits 4 labeled sections — leaf count:, leaf[, contains ErrConfig:, contains ErrSecret: — one per step.
Execute the file and main walks through collectLeaves, in that order.
Statements that matter
authGroup := fmt.Errorf("auth init: %w", errors.Join(ErrSecret, errors.New("expired cert")))
root := fmt.Errorf("startup failed: %w", errors.Join(ioGroup, authGroup))
for _, child := range x.Unwrap() {
collectLeaves(child, out)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Inspect Multi-Error Trees With errors.Join And Unwrap print when run?
- No setup needed: run the file and look for labeled lines like `leaf count:`, `leaf[`, `contains ErrConfig:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.