This repository has been archived by the owner on Aug 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
104 lines (80 loc) · 1.96 KB
/
context.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
package emperror
import (
"fmt"
"io"
)
// The implementation bellow is heavily influenced by go-kit's log context.
// With returns a new error with keyvals context appended to it.
// If the wrapped error is already a contextual error created by With
// keyvals is appended to the existing context, but a new error is returned.
func With(err error, keyvals ...interface{}) error {
if err == nil {
return nil
}
if len(keyvals) == 0 {
return err
}
var kvs []interface{}
// extract context from previous error
if c, ok := err.(*withContext); ok {
err = c.err
kvs = append(kvs, c.keyvals...)
if len(kvs)%2 != 0 {
kvs = append(kvs, nil)
}
}
kvs = append(kvs, keyvals...)
if len(kvs)%2 != 0 {
kvs = append(kvs, nil)
}
// Limiting the capacity of the stored keyvals ensures that a new
// backing array is created if the slice must grow in With.
// Using the extra capacity without copying risks a data race.
return &withContext{
err: err,
keyvals: kvs[:len(kvs):len(kvs)],
}
}
// Context extracts the context key-value pairs from an error (or error chain).
func Context(err error) []interface{} {
type contextor interface {
Context() []interface{}
}
var kvs []interface{}
ForEachCause(err, func(err error) bool {
if cerr, ok := err.(contextor); ok {
kvs = append(cerr.Context(), kvs...)
}
return true
})
return kvs
}
// withContext annotates an error with context.
type withContext struct {
err error
keyvals []interface{}
}
func (w *withContext) Error() string {
return w.err.Error()
}
// Context returns the appended keyvals.
func (w *withContext) Context() []interface{} {
return w.keyvals
}
func (w *withContext) Cause() error {
return w.err
}
func (w *withContext) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
_, _ = fmt.Fprintf(s, "%+v", w.Cause())
return
}
fallthrough
case 's':
_, _ = io.WriteString(s, w.Error())
case 'q':
_, _ = fmt.Fprintf(s, "%q", w.Error())
}
}