-
Notifications
You must be signed in to change notification settings - Fork 2
/
flatten.go
45 lines (38 loc) · 1003 Bytes
/
flatten.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
37
38
39
40
41
42
43
44
45
package karma
import (
"errors"
"fmt"
"strings"
)
func Flatten(err error) error {
if err, ok := err.(Karma); ok {
messages := []string{err.GetMessage()}
keyvalues := err.GetContext().GetKeyValuePairs()
err.Descend(
func(reason Reason) {
switch reason := reason.(type) {
case Karma:
messages = append(messages, reason.GetMessage())
values := reason.GetContext().GetKeyValuePairs()
if len(values) > 0 {
for i := 0; i < len(values); i += 2 {
keyvalues = append(keyvalues, values[i], values[i+1])
}
}
default:
messages = append(messages, fmt.Sprint(reason))
}
},
)
if len(keyvalues) > 0 {
pairs := make([]string, len(keyvalues)/2)
for i := 0; i < len(keyvalues); i += 2 {
pairs[i/2] = fmt.Sprintf("%s=%v", keyvalues[i], keyvalues[i+1])
}
return errors.New(strings.Join(messages, ": ") + " | " + strings.Join(pairs, " "))
} else {
return errors.New(strings.Join(messages, ": "))
}
}
return err
}