forked from workshop-depot/tinykv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathretry.go
56 lines (51 loc) · 1.24 KB
/
retry.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
// Code generated by github.com/dc0d/goreuse. DO NOT EDIT.
//go:generate goreuse -o retry.go -rn try=Try -rn retry=Retry github.com/dc0d/retry
package tinykv
import (
"time"
"github.com/pkg/errors"
)
// Try tries to run a function and recovers from a panic, in case
// one happens, and returns the error, if there are any.
func try(f func() error) (errRun error) {
defer func() {
if e := recover(); e != nil {
if err, ok := e.(error); ok {
errRun = err
return
}
errRun = errors.Errorf("RECOVERED, UNKNOWN ERROR: %+v", e)
}
}()
return f()
}
// Retry retries running a function, numberOfRetries times.
// If numberOfRetries < 0, it runs it forever as long as there are
// any errors. If there are no errors, it will return. If
// numberOfRetries > 1, it will sleep between two attemps,
// the default period is 5 seconds.
func retry(
f func() error,
numberOfRetries int,
onError func(error),
period ...time.Duration) {
p := time.Second * 5
if len(period) > 0 && period[0] > 0 {
p = period[0]
}
for numberOfRetries != 0 {
if numberOfRetries > 0 {
numberOfRetries--
}
if err := try(f); err != nil {
if onError != nil {
onError(err)
}
if numberOfRetries != 0 {
time.Sleep(p)
}
} else {
break
}
}
}