-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathio.go
62 lines (49 loc) · 1.19 KB
/
io.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
62
package internal
import (
"errors"
"fmt"
"io"
"os"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
)
// CloseWithErrLogf is making sure we log every error, even those from best effort tiny closers.
func CloseWithErrLogf(logger log.Logger, closer io.Closer, format string, a ...interface{}) {
err := closeIo(closer)
if err == nil {
return
}
if logger == nil {
logger = log.NewLogfmtLogger(os.Stderr)
}
level.Warn(logger).Log("msg", "detected close error", "err", fmt.Errorf(format+", %w", append(a, err)...))
}
// CloseWithErrCapturef runs function and on error return error by argument including the given error..
func CloseWithErrCapturef(err *error, closer io.Closer, format string, a ...interface{}) {
if err != nil {
cErr := closeIo(closer)
if cErr == nil {
return
}
mErr := MultiError{}
mErr.Add(*err)
mErr.Add(fmt.Errorf(format+", %w", append(a, cErr)...))
*err = mErr.Err()
return
}
cErr := closeIo(closer)
if cErr == nil {
return
}
*err = cErr
}
func closeIo(closer io.Closer) error {
err := closer.Close()
if err == nil {
return nil
}
if errors.Is(err, os.ErrClosed) {
return nil
}
return fmt.Errorf("error closing io.Closer: %w", err)
}