-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchaining.go
56 lines (47 loc) · 1.09 KB
/
chaining.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
package chaining
type Chain struct {
val interface{}
err error
}
// New is the root of the channing
// New(func(args...))
func New(val interface{}, err error) *Chain {
return &Chain{
val: val,
err: err,
}
}
// Next pass the result of the upstream to the next func
// if any error occured at any point of the upstream,
// no downstream will be involved, until there is a `Fail` deal with the error
func (c *Chain) Next(f func(c *Chain) (interface{}, error)) *Chain {
if c.err != nil {
return c
}
if val, err := f(c); err != nil {
c.err = err
} else {
c.val = val
}
return c
}
// NextWithFail is Similiar to Next,
// the different is NextWithFail will ignore the error that happended in the upstream.
// You should deal with the fail by yourself
func (c *Chain) NextWithFail(f func(c *Chain) (interface{}, error)) *Chain {
val, err := f(c)
if err == nil {
c.val = val
}
c.err = err
return c
}
// Fail deal with the first error that occured at the upstream of the chain
func (c *Chain) Fail(f func(err error)) *Chain {
if c.err == nil {
return c
}
f(c.err)
c.err = nil
return c
}