/
retry.go
75 lines (56 loc) · 1.45 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package retry
import (
"errors"
"github.com/fatih/color"
"time"
)
var Delay time.Duration
var NumRetries int
var PanicEnabled bool
func init() {
Delay = 2 * time.Second
NumRetries = 15
PanicEnabled = false
}
// Do accepts a function argument that returns an error. It will keep executing this
// function NumRetries times until no error is returned.
// Optionally pass another function as an argument that it will execute before retrying
// in case an error is returned from the first argument fuction.
func Do(args ...interface{}) error {
if len(args) == 0 {
panic("Wrong number of arguments")
}
task, ok := args[0].(func() error)
beforeRetry := func() {}
if len(args) > 1 {
beforeRetry, ok = args[1].(func())
}
if ok == false {
panic("Wrong Type of Arguments given to retry.Do")
}
retries := NumRetries
var atleastOneError error
atleastOneError = nil
err := errors.New("Non-Nil error")
for retries > 0 && err != nil {
err = task()
if err != nil {
atleastOneError = err
color.Magenta("\nError: %v\nRetrying #%d after %v", err, (NumRetries - retries + 1), Delay)
time.Sleep(Delay)
beforeRetry()
}
retries = retries - 1
}
if err != nil {
color.Red("\nError even after %d retries:\n%v", NumRetries, err)
if PanicEnabled == true {
panic(err)
}
return err
}
if atleastOneError != nil {
color.Cyan("\nRecovered from error: %v in %d tries\n", atleastOneError, (NumRetries - retries - 1))
}
return err
}