-
Notifications
You must be signed in to change notification settings - Fork 61
/
retry.go
44 lines (35 loc) · 852 Bytes
/
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
// Copyright 2020 VMware, Inc.
// SPDX-License-Identifier: Apache-2.0
package util
import (
"fmt"
"time"
"github.com/google/go-containerregistry/pkg/v1/remote/transport"
)
type NonRetryableError struct {
Message string
}
func (n NonRetryableError) Error() string {
return n.Message
}
func Retry(doFunc func() error) error {
var lastErr error
for i := 0; i < 5; i++ {
lastErr = doFunc()
if lastErr == nil {
return nil
}
if tranErr, ok := lastErr.(*transport.Error); ok {
if len(tranErr.Errors) > 0 {
if tranErr.Errors[0].Code == transport.UnauthorizedErrorCode {
return fmt.Errorf("Non-retryable error: %s", lastErr)
}
}
}
if nonRetryableError, ok := lastErr.(NonRetryableError); ok {
return nonRetryableError
}
time.Sleep(1 * time.Second)
}
return fmt.Errorf("Retried 5 times: %s", lastErr)
}