-
Notifications
You must be signed in to change notification settings - Fork 65
/
err.go
100 lines (78 loc) · 1.74 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
package errors
import (
"fmt"
"io"
"runtime"
"github.com/pkg/errors"
)
func callers() []uintptr {
var pcs [32]uintptr
l := runtime.Callers(3, pcs[:])
return pcs[:l]
}
// Error a error with caller stack information
type Error interface {
error
t()
}
var _ Error = (*item)(nil)
var _ fmt.Formatter = (*item)(nil)
type item struct {
msg string
stack []uintptr
}
func (i *item) Error() string {
return i.msg
}
func (i *item) t() {}
// Format used by go.uber.org/zap in Verbose
func (i *item) Format(s fmt.State, verb rune) {
io.WriteString(s, i.msg)
io.WriteString(s, "\n")
for _, pc := range i.stack {
fmt.Fprintf(s, "%+v\n", errors.Frame(pc))
}
}
// New create a new error
func New(msg string) Error {
return &item{msg: msg, stack: callers()}
}
// Errorf create a new error
func Errorf(format string, args ...interface{}) Error {
return &item{msg: fmt.Sprintf(format, args...), stack: callers()}
}
// Wrap with some extra message into err
func Wrap(err error, msg string) Error {
if err == nil {
return nil
}
e, ok := err.(*item)
if !ok {
return &item{msg: fmt.Sprintf("%s; %s", msg, err.Error()), stack: callers()}
}
e.msg = fmt.Sprintf("%s; %s", msg, e.msg)
return e
}
// Wrapf with some extra message into err
func Wrapf(err error, format string, args ...interface{}) Error {
if err == nil {
return nil
}
msg := fmt.Sprintf(format, args...)
e, ok := err.(*item)
if !ok {
return &item{msg: fmt.Sprintf("%s; %s", msg, err.Error()), stack: callers()}
}
e.msg = fmt.Sprintf("%s; %s", msg, e.msg)
return e
}
// WithStack add caller stack information
func WithStack(err error) Error {
if err == nil {
return nil
}
if e, ok := err.(*item); ok {
return e
}
return &item{msg: err.Error(), stack: callers()}
}