-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtry.go
50 lines (43 loc) · 854 Bytes
/
try.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
package try
import (
"errors"
"fmt"
)
// MaxRetries is the maximum number of retries
var MaxRetries = 3
// Do keep trying the function until max retry limit or no return error
func Do(fn func(attempt int) error, maxRetries ...int) error {
var (
err error
attempt = 1
maxAttempt = MaxRetries
)
if len(maxRetries) > 0 {
maxAttempt = maxRetries[0]
}
for {
func() {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()
err = fn(attempt)
}()
if err == nil {
break
}
attempt++
if attempt > maxAttempt {
if err != nil {
return err
}
return ErrMaxRetriesReached
}
}
return err
}
// IsMaxRetries is a function to check if the error has reached the maximum to try
func IsMaxRetries(err error) bool {
return errors.Is(err, ErrMaxRetriesReached)
}