-
Notifications
You must be signed in to change notification settings - Fork 0
/
err.go
131 lines (107 loc) · 1.98 KB
/
err.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package errors
import (
stderrors "errors"
"fmt"
"io"
"strings"
)
type Error struct {
*stack
Err error // 只会是外部错误,保持最早的栈
Message map[string]string // TODO 大多数应该都用不到
isTip bool
tipMsg string
}
func New(text string) *Error {
return &Error{
stack: callers(),
Err: stderrors.New(text),
}
}
func Wrap(err error) *Error {
if ee, ok := err.(*Error); ok {
return ee
}
return &Error{
stack: callers(),
Err: err,
}
}
// if Error is Upper。 must care where e is nil
func (e *Error) IsTip() *Error {
if e == nil {
return nil
}
e.isTip = true
return e
}
func (e *Error) WithMessage(key, text string) *Error {
if e == nil {
return nil
}
if e.Message == nil {
e.Message = make(map[string]string)
}
e.Message[key] = text
return e
}
func (e *Error) WithTip(text string) *Error {
if e == nil {
return nil
}
e.tipMsg = text
return e
}
func (e *Error) Error() string {
if e == nil {
return ""
}
if e.Err != nil {
msg := ""
if len(e.Message) > 0 {
msgs := make([]string, 0, len(e.Message))
for key, value := range e.Message {
msgs = append(msgs, fmt.Sprintf("%s: %s", key, value))
}
msg = fmt.Sprintf("[%s]", strings.Join(msgs, ", "))
}
return e.Err.Error() + msg
}
return ""
}
func (e *Error) E() error {
if e == nil {
return nil
}
return e
}
func (e *Error) Format(s fmt.State, verb rune) {
msgs := make([]string, 0, len(e.Message))
for key, value := range e.Message {
msgs = append(msgs, fmt.Sprintf("%s: %s", key, value))
}
msg := fmt.Sprintf("[%s]", strings.Join(msgs, ", "))
switch verb {
case 'v':
if s.Flag('+') {
io.WriteString(s, e.Error()+" ")
io.WriteString(s, msg)
e.stack.Format(s, verb)
return
}
fallthrough
case 's':
io.WriteString(s, e.Error())
case 'q':
fmt.Fprintf(s, "%q", e.Error())
}
}
func (e *Error) GetTipMsg() string {
if e.tipMsg != "" {
return e.tipMsg
}
if e.isTip {
return e.Error()
}
return ""
}