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.

GoResilience

Code

snippet
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

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.