-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregistry.go
More file actions
113 lines (90 loc) · 2.21 KB
/
registry.go
File metadata and controls
113 lines (90 loc) · 2.21 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package again
import (
"context"
"errors"
"net"
"net/http"
"sync"
)
// Registry holds a set of temporary errors.
type Registry struct {
mu sync.RWMutex
storage []error
}
// NewRegistry creates a new Registry.
func NewRegistry() *Registry {
return &Registry{}
}
// LoadDefaults loads a set of default temporary errors.
func (r *Registry) LoadDefaults() *Registry {
r.RegisterTemporaryErrors(
context.DeadlineExceeded,
http.ErrHandlerTimeout,
http.ErrServerClosed,
net.ErrClosed,
net.ErrWriteToConnected,
)
return r
}
// RegisterTemporaryError registers a temporary error.
func (r *Registry) RegisterTemporaryError(err error) {
r.RegisterTemporaryErrors(err)
}
// RegisterTemporaryErrors registers multiple temporary errors.
func (r *Registry) RegisterTemporaryErrors(errs ...error) {
r.mu.Lock()
defer r.mu.Unlock()
r.storage = append(r.storage, errs...)
}
// UnRegisterTemporaryError removes a temporary error.
func (r *Registry) UnRegisterTemporaryError(err error) {
r.UnRegisterTemporaryErrors(err)
}
// UnRegisterTemporaryErrors removes multiple temporary errors.
func (r *Registry) UnRegisterTemporaryErrors(errs ...error) {
r.mu.Lock()
defer r.mu.Unlock()
for _, target := range errs {
for i, e := range r.storage {
if errors.Is(e, target) {
r.storage = append(r.storage[:i], r.storage[i+1:]...)
break
}
}
}
}
// ListTemporaryErrors returns all temporary errors in the registry.
func (r *Registry) ListTemporaryErrors() []error {
r.mu.RLock()
defer r.mu.RUnlock()
out := make([]error, len(r.storage))
copy(out, r.storage)
return out
}
// Len returns the number of registered temporary errors.
func (r *Registry) Len() int {
r.mu.RLock()
defer r.mu.RUnlock()
return len(r.storage)
}
// Clean removes all temporary errors from the registry.
func (r *Registry) Clean() {
r.mu.Lock()
defer r.mu.Unlock()
r.storage = nil
}
// IsTemporaryError reports whether err matches any of the temporary errors.
func (r *Registry) IsTemporaryError(err error, errs ...error) bool {
var tempErrors []error
if errs == nil {
tempErrors = r.ListTemporaryErrors()
} else {
tempErrors = errs
}
for _, te := range tempErrors {
if errors.Is(err, te) {
return true
}
}
return false
}