go / expert
Snippet
Hierarchical Multi-Error Tree Inspection via Custom Unwrap Slices
Go 1.20 introduced support for multi-error unwrapping by defining an `Unwrap() []error` method on custom error types. This allows standard functions like `errors.Is` and `errors.As` to recursively traverse tree-like error structures across multiple branches without manual iteration.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package mainimport ("errors""fmt""io")type MultiError struct {Errors []error}func (m *MultiError) Error() string {return fmt.Sprintf("encountered %d combined errors", len(m.Errors))}func (m *MultiError) Unwrap() []error {return m.Errors}func main() {err1 := fmt.Errorf("read failure: %w", io.EOF)err2 := errors.New("connection reset")joined := &MultiError{Errors: []error{err1, err2}}if errors.Is(joined, io.EOF) {fmt.Println("Matched io.EOF deep within MultiError slice!")}}
Breakdown
1
func (m *MultiError) Unwrap() []error {
Implements Go 1.20+ multi-error unwrapping interface allowing errors.Is and errors.As to traverse multiple error branches.
2
err1 := fmt.Errorf("read failure: %w", io.EOF)
Wraps a standard sentinel error using %w verb to preserve the underlying error cause.
3
if errors.Is(joined, io.EOF) {
Recursively scans the slice of errors returned by Unwrap() to detect target error types.