实现说明
全部逻辑都在函数 collectLeaves、main中。
这个示例中仅有的重复出现在 for _, child := range x.Unwrap() 里。
使用要点
- 免除安装环节:全篇代码完全依赖标准库组件。
- 每一步打印都带着自己的标签:
leaf count:、leaf[、contains ErrConfig:。 - 执行文件,
main会按顺序走完collectLeaves。
常见问题
运行「用 errors.Join 与 Unwrap 遍历多错误树」会打印什么?
运行文件本身,leaf count:、leaf[、contains ErrConfig: 这些前缀各对应一段演示逻辑。
签名一览:func collectLeaves(err error, out *[]error)
核心语句
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)
}
代码示例
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))
}