Debian Codegraph @

logerrcapture/doc.go

raw symbols SCIP
1 // Copyright (c) The EfficientGo Authors.
2 // Licensed under the Apache License 2.0.
3
4 // Package logerrcapture implements robust error handling in defer statements using provided logger.
5 //
6 // The Close a `io.Closer` interface or execute any function that returns error safely while logging error.
7 // It's often forgotten but it's a caller responsibility to close all implementations of `Closer`,
8 // such as *os.File or io.ReaderCloser. Commonly we would use:
9 //
10 // defer closer.Close()
11 //
12 // This is wrong. Close() usually return important error (e.g for os.File the actual file flush might happen and fail on `Close` method).
13 // It's very important to *always* check error. `logerrcapture` provides utility functions to capture error and log it via provided
14 // logger, while still allowing to put them in a convenient `defer` statement:
15 //
16 // func <...>(...) (err error) {
17 // ...
18 // defer logerrcapture.Do(logger, closer.Close, "log format message")
19 //
20 // ...
21 // }
22 //
23 // If Close returns error, `logerrcapture.Do` will capture it, add to input error if not nil and return by argument.
24 //
25 // Example:
26 //
27 // func DoAndClose(f *os.File, logger logerrcapture.Logger) error {
28 // defer logerrcapture.Do(logger, f.Close, "close file at the end")
29 //
30 // // Do something...
31 // if err := do(); err != nil {
32 // return err
33 // }
34 //
35 // return nil
36 // }
37 //
38 // The logerrcapture.ExhaustClose function provide the same functionality but takes an io.ReadCloser and exhausts the whole
39 // reader before closing. This is useful when trying to use http keep-alive connections because for the same connection
40 // to be re-used the whole response body needs to be exhausted.
41 //
42 // Recommended: Check https://pkg.go.dev/github.com/efficientgo/tools/pkg/errcapture if you want to return error instead of just logging (causing
43 // hard error).
44 package logerrcapture