go / expert
Snippet
Multi-Error Aggregation and Hierarchical Type Matching with Slice Unwrapping
Go 1.20 introduced support for Unwrap() []error in composite custom errors. Implementing this method enables stdlib errors.Is and errors.As to recursively traverse tree-like error graphs, allowing callers to inspect multiple aggregated failures 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
30
31
32
33
34
35
36
package mainimport ("errors""fmt""strings")type MultiError struct {Errors []error}func (m *MultiError) Error() string {var msgs []stringfor _, err := range m.Errors {msgs = append(msgs, err.Error())}return fmt.Sprintf("%d errors occurred: %s", len(m.Errors), strings.Join(msgs, "; "))}func (m *MultiError) Unwrap() []error {return m.Errors}type NetworkTimeoutError struct {Addr string}func (e *NetworkTimeoutError) Error() string {return fmt.Sprintf("timeout accessing %s", e.Addr)}func Process(err error) bool {var target *NetworkTimeoutErrorreturn errors.As(err, &target)}
Breakdown
1
func (m *MultiError) Unwrap() []error { return m.Errors }
Exposes the internal slice of errors to allow standard library errors package traversal.
2
return errors.As(err, &target)
Searches the unwrapped multi-error hierarchy for a specific error type match.