-
Notifications
You must be signed in to change notification settings - Fork 56
/
formatted_error.go
67 lines (55 loc) · 1.23 KB
/
formatted_error.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"errors"
"strings"
)
func formattedError(err error) string {
var formatted string
i := -1
for {
i++
reason := err.Error()
if err = errors.Unwrap(err); err == nil {
formatted = appendError(formatted, reason, i, true)
return formatted
}
reason = strings.TrimSuffix(reason, err.Error())
reason = strings.TrimRight(reason, " ")
reason = strings.TrimSuffix(reason, ":")
formatted = appendError(formatted, reason, i, false)
}
}
func appendError(errorMessage, reason string, i int, last bool) string {
if i == 0 {
errorMessage = indentedReason(reason, i)
} else {
errorMessage += "\n"
errorMessage += indentedReason(reason, i)
}
if !last {
errorMessage += ":"
}
return errorMessage
}
func indentedReason(reason string, level int) string {
var lines []string
split := strings.Split(reason, "\n")
for _, line := range split {
line = strings.TrimLeft(line, " ")
line = strings.TrimRight(line, "\n")
line = strings.TrimRight(line, " ")
if line == "" {
continue
}
lines = append(lines, line)
}
var indented string
for i, line := range lines {
indented += strings.Repeat(" ", level)
indented += line
if i != len(lines)-1 {
indented += "\n"
}
}
return indented
}