| 1 | // Copyright (c) The EfficientGo Authors. |
| 2 | // Licensed under the Apache License 2.0. |
| 3 | |
| 4 | // Initially copied from Thanos |
| 5 | // |
| 6 | // Copyright (c) The Thanos Authors. |
| 7 | // Licensed under the Apache License 2.0. |
| 8 | |
| 9 | package errcapture |
| 10 | |
| 11 | import ( |
| 12 | "io" |
| 13 | "os" |
| 14 | |
| 15 | "github.com/efficientgo/core/errors" |
| 16 | "github.com/efficientgo/core/merrors" |
| 17 | ) |
| 18 | |
| 19 | type doFunc func() error |
| 20 | |
| 21 | // Do runs function and on error return error by argument including the given error (usually |
| 22 | // from caller function). |
| 23 | func Do(err *error, doer doFunc, format string, a ...interface{}) { |
| 24 | derr := doer() |
| 25 | if err == nil { |
| 26 | return |
| 27 | } |
| 28 | |
| 29 | // For os closers, it's a common case to double close. From reliability purpose this is not a problem it may only indicate |
| 30 | // surprising execution path. |
| 31 | if errors.Is(derr, os.ErrClosed) { |
| 32 | return |
| 33 | } |
| 34 | |
| 35 | *err = merrors.New(*err, errors.Wrapf(derr, format, a...)).Err() |
| 36 | } |
| 37 | |
| 38 | // ExhaustClose closes the io.ReadCloser with error capture but exhausts the reader before. |
| 39 | func ExhaustClose(err *error, r io.ReadCloser, format string, a ...interface{}) { |
| 40 | _, copyErr := io.Copy(io.Discard, r) |
| 41 | |
| 42 | Do(err, r.Close, format, a...) |
| 43 | |
| 44 | // Prepend the io.Copy error. |
| 45 | *err = merrors.New(copyErr, *err).Err() |
| 46 | } |