-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patherrors.go
222 lines (197 loc) · 5.14 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
package errors
import (
"bytes"
"encoding/json"
"fmt"
"path/filepath"
"runtime"
"strconv"
)
// Error is an interface that extends the builtin error interface with inner
// errors and stack traces.
type Error interface {
// Message returns the error message of the error.
Message() string
// Inner returns the inner error that this error wraps.
Inner() error
// Stack returns the stack trace that led to the error.
Stack() Frames
error
}
var (
// This setting enables a stack trace to be printed when an Error is being
// marshaled.
//
// err := errors.New("example")
// b, _ := json.Marshal(err) // {"message":"example","stack":[{"file":"<file>","line":<line>,"func": "<function>"},...]}
MarshalTrace = false
)
// Type errtype is the default implementation of the Error interface. It is not
// exported so users can only use it via the New or Wrap functions.
type errtype struct {
message string
inner error
stack Frames
}
// Message returns the error message of the error.
func (t *errtype) Message() string {
return t.message
}
// Inner returns the inner error that this error wraps.
func (t *errtype) Stack() Frames {
return t.stack
}
// Stack returns the stack trace that led to the error.
func (t *errtype) Inner() error {
return t.inner
}
// Error implements the standard library error interface.
func (t *errtype) Error() string {
if t.inner != nil {
return t.message + ". " + t.inner.Error()
}
return t.message
}
// Format implements the standard library fmt.Formatter interface. Credit to
// Dave Cheney's github.com/pkg/errors.
func (t *errtype) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
fmt.Fprintf(s, "%s", t.message)
if t.inner != nil {
fmt.Fprintf(s, ". %s", t.inner.Error())
}
if s.Flag('+') {
fmt.Fprint(s, "\n")
fmt.Fprintf(s, "%s", t.stack.String())
}
case 's':
fmt.Fprintf(s, "%s", t.message)
if t.inner != nil {
fmt.Fprintf(s, ". %s", t.inner.Error())
}
case 'q':
fmt.Fprintf(s, "%q", t.message)
}
}
func (t *errtype) MarshalJSON() ([]byte, error) {
b, err := t.stack.MarshalJSON()
if err != nil {
return b, err
}
var buf bytes.Buffer
fmt.Fprint(&buf, "{")
fmt.Fprintf(&buf, `"message":%q`, t.message)
if t.inner != nil {
fmt.Fprintf(&buf, `,"inner":%q`, t.inner)
}
if t.stack != nil {
fmt.Fprintf(&buf, `,"stack":%s`, b)
}
fmt.Fprint(&buf, "}")
return buf.Bytes(), nil
}
func sprintf(format string, args ...interface{}) string {
return fmt.Sprintf(format, args...)
}
// New creates a new Error with the supplied message.
func New(message string) Error {
return new(message, 3)
}
// Errorf creates a new Error with the supplied message and arguments formatted
// in the manner of fmt.Printf.
func Errorf(message string, args ...interface{}) Error {
return new(sprintf(message, args...), 3)
}
func new(message string, skip int) Error {
return &errtype{
message: message,
stack: Stack(skip),
}
}
// Wrap creates a new Error that wraps err.
func Wrap(err error, message string) Error {
return wrap(err, message, 3)
}
// Wrapf creates a new Error that wraps err formatted in the manner of
// fmt.Printf.
func Wrapf(err error, message string, args ...interface{}) Error {
return wrap(err, sprintf(message, args...), 3)
}
func wrap(err error, message string, skip int) Error {
if errT, ok := err.(*errtype); ok {
errT.stack = nil // drop the stack trace of the inner error.
} else {
err = &errtype{message: err.Error()}
}
return &errtype{
message: message,
inner: err,
stack: Stack(skip),
}
}
// Frame contains information for a single stack frame.
type Frame struct {
// File is the path to the file of the caller.
File string `json:"file"`
// Line is the line in the file where the function call was made.
Line int `json:"line"`
// Func is the name of the caller.
Func string `json:"func"`
}
type Frames []Frame
// String is used to satisfy the fmt.Stringer interface. It formats the stack
// trace as a comma separated list of "file:line function".
func (f Frames) String() string {
var buf bytes.Buffer
for i, frame := range f {
buf.WriteByte('\t')
buf.WriteString(frame.Func)
buf.WriteByte('(')
buf.WriteString(frame.File)
buf.WriteByte(':')
buf.WriteString(strconv.Itoa(frame.Line))
buf.WriteByte(')')
if i < len(f)-1 {
buf.WriteByte('\n')
}
}
return buf.String()
}
func (f Frames) MarshalJSON() ([]byte, error) {
if !MarshalTrace {
return []byte("[]"), nil
}
b := bytes.NewBuffer(nil)
b.WriteByte('[')
e := json.NewEncoder(b)
for i, frame := range f {
err := e.Encode(frame)
if err != nil {
return b.Bytes(), err
}
if i+1 < len(f) {
b.WriteByte(',')
}
}
b.WriteByte(']')
return b.Bytes(), nil
}
// Stack returns the stack trace of the function call, while skipping the first
// skip frames.
func Stack(skip int) Frames {
callers := make([]uintptr, 10)
n := runtime.Callers(skip, callers)
callers = callers[:n-2] // skip runtime.main and runtime.goexit function calls
frames := make(Frames, len(callers))
for i, caller := range callers {
fn := runtime.FuncForPC(caller)
file, line := fn.FileLine(caller)
frames[i] = Frame{
File: filepath.Base(file),
Line: line,
Func: fn.Name(),
}
}
return frames
}