-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathxdefer.go
112 lines (95 loc) · 2.27 KB
/
xdefer.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
// Package xdefer implements an extremely useful function, Errorf, to annotate all errors returned from a function transparently.
package xdefer
import (
"fmt"
"strings"
"golang.org/x/xerrors"
)
type deferError struct {
s string
err error
frame xerrors.Frame
}
var _ interface {
xerrors.Wrapper
xerrors.Formatter
Is(error) bool
} = deferError{}
func (e deferError) Unwrap() error {
return e.err
}
func (e deferError) Format(f fmt.State, c rune) {
xerrors.FormatError(e, f, c)
}
// Used to detect if there is a duplicate frame as a result
// of using xdefer and if so to ignore it.
type fakeXerrorsPrinter struct {
s []string
}
func (fp *fakeXerrorsPrinter) Print(v ...interface{}) {
fp.s = append(fp.s, fmt.Sprint(v...))
}
func (fp *fakeXerrorsPrinter) Printf(f string, v ...interface{}) {
fp.s = append(fp.s, fmt.Sprintf(f, v...))
}
func (fp *fakeXerrorsPrinter) Detail() bool {
return true
}
func (e deferError) shouldPrintFrame(p xerrors.Printer) bool {
fm, ok := e.err.(xerrors.Formatter)
if !ok {
return true
}
fp := &fakeXerrorsPrinter{}
e.frame.Format(fp)
fp2 := &fakeXerrorsPrinter{}
_ = fm.FormatError(fp2)
if len(fp.s) >= 2 && len(fp2.s) >= 3 {
if fp.s[1] == fp2.s[2] {
// We don't need to print our frame into the real
// xerrors printer as the next error will have it.
return false
}
}
return true
}
func (e deferError) FormatError(p xerrors.Printer) error {
if e.s == "" {
if e.shouldPrintFrame(p) {
e.frame.Format(p)
}
return e.err
}
p.Print(e.s)
if p.Detail() && e.shouldPrintFrame(p) {
e.frame.Format(p)
}
return e.err
}
func (e deferError) Is(err error) bool {
return xerrors.Is(e.err, err)
}
func (e deferError) Error() string {
if e.s == "" {
fp := &fakeXerrorsPrinter{}
e.frame.Format(fp)
if len(fp.s) < 1 {
return e.err.Error()
}
return fmt.Sprintf("%v: %v", strings.TrimSpace(fp.s[0]), e.err)
}
return fmt.Sprintf("%v: %v", e.s, e.err)
}
// Errorf makes it easy to defer annotate an error for all return paths in a function.
// See the tests for how it's used.
//
// Pass s == "" to only annotate the location of the return.
func Errorf(err *error, s string, v ...interface{}) {
if *err != nil {
*err = deferError{
s: fmt.Sprintf(s, v...),
err: *err,
frame: xerrors.Caller(1),
}
}
}