-
Notifications
You must be signed in to change notification settings - Fork 0
/
func.go
51 lines (46 loc) · 1.06 KB
/
func.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
package retry
import (
"context"
"errors"
)
// DoValue executes f with retrying policy.
// It is a shorthand of Policy.Start and Retrier.Continue.
// If f returns an error, retry to execute f until f returns nil error.
// If the error is wrapped by [MarkTemporary], DoValue doesn't retry and returns the error.
func DoValue[T any](ctx context.Context, policy *Policy, f func() (T, error)) (T, error) {
var zero T
var err error
var target *temporary
retrier := policy.Start(ctx)
for retrier.Continue() {
var v T
v, err = f()
if err == nil {
return v, nil
}
// short cut for calling Unwrap
if err, ok := err.(*myError); ok {
if err.tmp {
continue
}
return zero, err.error
}
if target == nil {
// lazy allocation of target
target = new(temporary)
}
if errors.As(err, target) {
if !(*target).temporary() {
return zero, err
}
}
}
if err := retrier.err; err != nil {
return zero, err
}
if err, ok := err.(*myError); ok {
// Unwrap the error if it's marked as temporary.
return zero, err.error
}
return zero, err
}