-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
141 lines (110 loc) · 2.21 KB
/
errors.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
132
133
134
135
136
137
138
139
140
141
package fmx
import (
"fmt"
"runtime"
"strings"
)
type ErrorWithPos interface {
error
Where() []string
String() string
}
func Errorf(code int, format string, a ...interface{}) ErrorWithPos {
e := &errorString{}
e.s = fmt.Sprintf(format, a...)
e.pos = make([]string, 0, 5)
e.code = code
pc, file, lineno, ok := runtime.Caller(1)
if ok {
e.pos = append(e.pos, fmt.Sprintf("%s:%d %s", file, lineno, runtime.FuncForPC(pc).Name()))
}
return e
}
func Error(err error, code ...int) ErrorWithPos {
if err == nil {
return nil
}
var stackinfo string
pc, file, lineno, ok := runtime.Caller(1)
if ok {
stackinfo = fmt.Sprintf("%s:%d %s", file, lineno, runtime.FuncForPC(pc).Name())
}
if pErr, ok := err.(*errorString); ok {
if len(stackinfo) > 0 {
pErr.pos = append(pErr.pos, stackinfo)
}
if len(code) > 0 {
pErr.code = code[0]
}
return pErr
} else {
e := &errorString{}
e.s = err.Error()
e.pos = make([]string, 0, 5)
e.code = 0
if len(stackinfo) > 0 {
e.pos = append(e.pos, stackinfo)
}
if len(code) > 0 {
e.code = code[0]
}
return e
}
}
//append text description to err, return a new err
func ErrorAppend(err error, szExtra ...string) ErrorWithPos {
if err == nil {
return nil
}
var stackinfo string
pc, file, lineno, ok := runtime.Caller(1)
if ok {
stackinfo = fmt.Sprintf("%s:%d %s", file, lineno, runtime.FuncForPC(pc).Name())
}
e := &errorString{}
e.s = err.Error()
e.pos = make([]string, 0, 5)
e.code = 0
if len(szExtra) > 0 {
e.s += strings.Join(szExtra, "")
}
if pErr, ok := err.(*errorString); ok {
e.pos = append(e.pos, pErr.pos...)
e.code = pErr.code
}
if len(stackinfo) > 0 {
e.pos = append(e.pos, stackinfo)
}
return e
}
func ErrCode(err error, def ...int) int {
var code int = 0
if len(def) > 0 {
code = def[0]
}
if err == nil {
return code
}
if pErr, ok := err.(*errorString); ok {
return pErr.code
}
return code
}
type errorString struct {
pos []string
s string
code int
}
func (e *errorString) Where() []string {
return e.pos
}
func (e *errorString) Error() string {
return e.s
}
func (e *errorString) String() string {
szErr := e.s
for _, item := range e.pos {
szErr += "\r\n" + item
}
return szErr
}