| 1 |
package retrier |
| 2 |
|
| 3 |
import "errors" |
| 4 |
|
| 5 |
// Action is the type returned by a Classifier to indicate how the Retrier should proceed. |
| 6 |
type Action int |
| 7 |
|
| 8 |
const ( |
| 9 |
Succeed Action = iota // Succeed indicates the Retrier should treat this value as a success. |
| 10 |
Fail // Fail indicates the Retrier should treat this value as a hard failure and not retry. |
| 11 |
Retry // Retry indicates the Retrier should treat this value as a soft failure and retry. |
| 12 |
) |
| 13 |
|
| 14 |
// Classifier is the interface implemented by anything that can classify Errors for a Retrier. |
| 15 |
type Classifier interface { |
| 16 |
Classify(error) Action |
| 17 |
} |
| 18 |
|
| 19 |
// DefaultClassifier classifies errors in the simplest way possible. If |
| 20 |
// the error is nil, it returns Succeed, otherwise it returns Retry. |
| 21 |
type DefaultClassifier struct{} |
| 22 |
|
| 23 |
// Classify implements the Classifier interface. |
| 24 |
func (c DefaultClassifier) Classify(err error) Action { |
| 25 |
if err == nil { |
| 26 |
return Succeed |
| 27 |
} |
| 28 |
|
| 29 |
return Retry |
| 30 |
} |
| 31 |
|
| 32 |
// WhitelistClassifier classifies errors based on a whitelist. If the error is nil, it |
| 33 |
// returns Succeed; if the error is in the whitelist, it returns Retry; otherwise, it returns Fail. |
| 34 |
type WhitelistClassifier []error |
| 35 |
|
| 36 |
// Classify implements the Classifier interface. |
| 37 |
func (list WhitelistClassifier) Classify(err error) Action { |
| 38 |
if err == nil { |
| 39 |
return Succeed |
| 40 |
} |
| 41 |
|
| 42 |
for _, pass := range list { |
| 43 |
if errors.Is(err, pass) { |
| 44 |
return Retry |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
return Fail |
| 49 |
} |
| 50 |
|
| 51 |
// BlacklistClassifier classifies errors based on a blacklist. If the error is nil, it |
| 52 |
// returns Succeed; if the error is in the blacklist, it returns Fail; otherwise, it returns Retry. |
| 53 |
type BlacklistClassifier []error |
| 54 |
|
| 55 |
// Classify implements the Classifier interface. |
| 56 |
func (list BlacklistClassifier) Classify(err error) Action { |
| 57 |
if err == nil { |
| 58 |
return Succeed |
| 59 |
} |
| 60 |
|
| 61 |
for _, pass := range list { |
| 62 |
if errors.Is(err, pass) { |
| 63 |
return Fail |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
return Retry |
| 68 |
} |