-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflerr.go
61 lines (49 loc) · 1.2 KB
/
flerr.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
51
52
53
54
55
56
57
58
59
60
61
package flerr
import (
"errors"
"fmt"
)
// Cleaner helps with handling errors from deferred functions and doing defers
// in loop blocks.
type Cleaner struct {
items []func() error
}
// Add adds a cleanup function.
func (c *Cleaner) Add(fn func() error) {
c.items = append(c.items, fn)
}
// Adds a cleanup function together with a message format that will be used to
// construct an error that wraps any error returned by the cleanup function.
func (c *Cleaner) Addf(fn func() error, format string, a ...any) {
c.items = append(c.items, func() error {
err := fn()
if err != nil {
msg := fmt.Sprintf(format, a...)
return fmt.Errorf("%s: %w", msg, err)
}
return nil
})
}
// Flush runs all cleanup functions and returns the join of all errors.
func (c *Cleaner) Flush() error {
var errs []error
for _, fn := range c.items {
err := fn()
if err != nil {
errs = append(errs, err)
}
}
c.items = c.items[0:0]
if len(errs) == 0 {
return nil
}
return errors.Join(errs...)
}
// FlushTo runs all cleanup functions and joins outErr with any errors that
// occurred.
func (c *Cleaner) FlushTo(outErr *error) {
err := c.Flush()
if err != nil {
*outErr = errors.Join(*outErr, err)
}
}