-
Notifications
You must be signed in to change notification settings - Fork 1
/
format.go
90 lines (77 loc) · 1.85 KB
/
format.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package cerrors
import (
"fmt"
"io"
"strings"
)
type withOwnMessage interface {
OwnMessage() string
}
type withFrame interface {
Frame() Frame
}
type withUnwrap interface {
Unwrap() error
}
func Format(err error, s io.Writer, withFunctions bool) {
var prefix string
for err != nil {
next := getNext(err)
fmt.Fprintln(s, prefix+getOwnMessage(err, next))
if wFrame, ok := err.(withFrame); ok {
wFrame.Frame().Format(s, withFunctions)
}
prefix = " - "
err = next
}
}
func getOwnMessage(err, next error) string {
if wMessage, ok := err.(withOwnMessage); ok {
return wMessage.OwnMessage()
} else if next != nil {
return unwrapMessageStr(err.Error(), next.Error())
} else {
return err.Error()
}
}
func getNext(err error) error {
if wUnwrap, ok := err.(withUnwrap); ok {
return wUnwrap.Unwrap()
}
return nil
}
// UnwrapMessage returns the portion of the error message which does not repeat
// in the wrapped error.
//
// Examples:
//
// err := errors.New("couldn't")
//
// UnwrapMessage(fmt.Errorf("doing foo: %w", err)) // => "doing foo"
// UnwrapMessage(fmt.Errorf("doing foo %w", err)) // => "doing foo"
// UnwrapMessage(fmt.Errorf("failed (%w) while doing foo", err))) // => "failed (*) while doing foo"
func UnwrapMessage(err error) string {
msg := err.Error()
if wrapper, ok := err.(withUnwrap); ok {
wrapped := wrapper.Unwrap()
if wrapped != nil {
if withOwnMessage, ok := wrapped.(withOwnMessage); ok {
return withOwnMessage.OwnMessage()
}
wrappedMsg := wrapped.Error()
return unwrapMessageStr(msg, wrappedMsg)
}
}
return msg
}
func unwrapMessageStr(parent, child string) string {
msg := parent
if idx := strings.Index(parent, child); idx > 0 {
if idx+len(child) == len(parent) {
msg = strings.TrimRight(parent[:idx], ": ")
} else {
msg = parent[:idx] + "*" + parent[idx+len(child):]
}
}
return msg
}