-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.go
More file actions
70 lines (59 loc) · 1.27 KB
/
Copy patherror.go
File metadata and controls
70 lines (59 loc) · 1.27 KB
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
package retry
import (
"errors"
"fmt"
)
// ShouldRetryFunc 根据错误判断是否应该停止重试
// 参数说明:
// - error: 需要处理的错误
//
// 返回值说明:
// - ok: 是否应该重试,true表示继续重试,false表示停止重试
type ShouldRetryFunc func(error) bool
type RetryError struct {
Code string
Cause error
}
func (e *RetryError) Error() string {
if e.Code != "" {
return fmt.Sprintf("Code: %s, Cause: %s", e.Code, e.Cause.Error())
}
return fmt.Sprintf("Retry Cause: %s", e.Error())
}
// 实现errors.Is链式比较
func (e *RetryError) Unwrap() error {
return e.Cause
}
// 实现errors.Is比较
func (e *RetryError) Is(target error) bool {
if re, ok := target.(*RetryError); ok {
return re.Code == e.Code
}
return false
}
func NewRetryError(code string, cause error) *RetryError {
return &RetryError{
Code: code,
Cause: cause,
}
}
func WrapError(code string, cause error) error {
if cause == nil {
return nil
}
// 原错误是否已经是RetryError
var re *RetryError
if errors.As(cause, &re) {
return re
}
return &RetryError{
Code: code,
Cause: cause,
}
}
func WrapErrorWithShould(code string, cause error, should ShouldRetryFunc) error {
if should(cause) {
return WrapError(code, cause)
}
return cause
}