forked from nqmt/goerror
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherror.go
119 lines (89 loc) · 1.97 KB
/
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
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
package goerror
import (
"fmt"
)
type Error interface {
Error() string
ErrorWithCause() string
PrintInput() string
StackTrace() string
Cause() string
IsCodeEqual(err error) bool
GetReasons() []*Reason
AddReason(fieldName, reason string, value interface{})
Input() interface{}
WithCause(cause error) Error
WithInput(input interface{}) Error
WithKeyValueInput(inputs ...interface{}) Error
WithExtendMsg(msg string) Error
}
type GoError struct {
Status int
Code string
Msg string
ExtendMsg string
cause string
reasons []*Reason
input interface{}
frames []*frame
}
func (e *GoError) Error() string {
if e.cause != "" {
return fmt.Sprintf("%s: %s - %s", e.Code, e.Msg, e.cause)
}
return fmt.Sprintf("%s: %s", e.Code, e.Msg)
}
func (e *GoError) PrintInput() string {
if e.input == nil {
return ""
}
return fmt.Sprintf("%v", e.input)
}
func (e *GoError) Input() interface{} {
return e.input
}
func (e *GoError) Cause() string {
return e.cause
}
func (e *GoError) ErrorWithCause() string {
return fmt.Sprintf("%s - %s", e.Error(), e.Cause())
}
func (e *GoError) IsCodeEqual(err error) bool {
if ge, ok := err.(*GoError); ok {
return ge.Code == e.Code
}
return false
}
func (e *GoError) WithCause(cause error) Error {
e.cause = cause.Error()
e.frames = trace(DefaultStackTraceSkipLine)
return e
}
func (e *GoError) WithInput(input interface{}) Error {
e.input = input
return e
}
func (e *GoError) WithExtendMsg(extendMsg string) Error {
e.ExtendMsg = extendMsg
return e
}
func (e *GoError) WithKeyValueInput(keyValues ...interface{}) Error {
if len(keyValues) == 1 && keyValues[0] == nil {
return e
}
if len(keyValues)%2 != 0 {
e.input = keyValues
return e
}
fields := map[string]interface{}{}
for i := 0; i*2 < len(keyValues); i++ {
key, ok := keyValues[i*2].(string)
if !ok {
fields[fmt.Sprintf("errf_%d", i)] = keyValues[i*2+1]
continue
}
fields[key] = keyValues[i*2+1]
}
e.input = fields
return e
}