-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrap.go
66 lines (57 loc) · 1.16 KB
/
wrap.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
package e5
import "testing"
// WrapFunc wraps an error to form a new one.
//
// Instances must follow these rules:
// if argument is nil, return value must be nil
type WrapFunc func(err error) error
var _ error = WrapFunc(nil)
var Wrap = WrapFunc(func(err error) error {
return err
})
func (w WrapFunc) With(args ...error) WrapFunc {
if len(args) == 0 {
return w
}
return w.with(args...)
}
func (w WrapFunc) with(args ...error) WrapFunc {
// convert to WrapFuncs
for i, arg := range args {
switch arg := arg.(type) {
case WrapFunc:
case error:
args[i] = With(arg)
}
}
return func(err error) error {
for _, arg := range args {
if err == nil {
return nil
}
wrapped := arg.(WrapFunc)(err)
if wrapped == nil {
return nil
}
if _, ok := wrapped.(Error); !ok {
wrapped = Join(wrapped, err)
}
err = wrapped
}
return err
}
}
func (w WrapFunc) Error() string {
panic("should not used as error")
}
func (w WrapFunc) Assign(p *error) {
if p != nil && *p != nil {
*p = w(*p)
}
}
// TestWrapFunc tests a WrapFunc instance
func TestWrapFunc(t *testing.T, fn WrapFunc) {
if fn(nil) != nil {
t.Fatal("should return nil")
}
}