package inspect import ( "reflect" "strings" "unicode/utf8" ) // node is an error in the tree with its message, computed once. type node struct { err error msg string kids []node } func build(err error) node { n := node{err: err, msg: err.Error()} switch e := err.(type) { case interface{ Unwrap() []error }: causes := e.Unwrap() if len(causes) > 0 { n.kids = make([]node, 0, len(causes)) for _, cause := range causes { if cause != nil { n.kids = append(n.kids, build(cause)) } } } case interface{ Unwrap() error }: if cause := e.Unwrap(); cause != nil { n.kids = []node{build(cause)} } } return n } // header returns the enabled metadata for err and its width. func header(err error, cfg config) (string, int) { var labels []string if cfg.types { labels = append(labels, reflect.TypeOf(err).String()) } if cfg.annotations { labels = append(labels, annotations(err, cfg.targets)...) } if len(labels) == 0 { return "", 0 } tag := "[" + strings.Join(labels, " ") + "]" return tag, utf8.RuneCountInString(tag) } // annotations reports the custom Is and As methods of err, labeled with the targets they match. func annotations(err error, targets []any) []string { var labels []string if m, ok := err.(interface{ Is(error) bool }); ok { labels = append(labels, label("Is", matchingTypes(targets, func(t any) bool { e, ok := t.(error) return ok && m.Is(e) }))) } if m, ok := err.(interface{ As(any) bool }); ok { labels = append(labels, label("As", matchingTypes(targets, func(t any) bool { v := reflect.ValueOf(t) return v.Kind() == reflect.Pointer && !v.IsNil() && m.As(t) }))) } return labels } func matchingTypes(targets []any, match func(any) bool) []string { var names []string for _, t := range targets { if match(t) { names = append(names, reflect.TypeOf(t).String()) } } return names } func label(name string, matched []string) string { if len(matched) == 0 { return name } return name + "(" + strings.Join(matched, ", ") + ")" } // ownMessage returns the message of n without the messages of its children. func ownMessage(n node) string { own := n.msg for _, kid := range n.kids { own = strings.Replace(own, kid.msg, "", 1) } return strings.Trim(own, " \t\r\n:") }