Repository navigation
Expand file tree
/
Copy patherrdefer.go
More file actions
65 lines (60 loc) · 1.73 KB
/
Copy patherrdefer.go
File metadata and controls
65 lines (60 loc) · 1.73 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
package errx
import (
"errors"
"io"
)
// OnError runs cleanup ONLY if *errp is non-nil when the enclosing
// function returns — the Zig `errdefer` semantics Go's plain `defer`
// cannot express without a hand-written `if *errp != nil` inside every
// deferred closure. Use it to roll back partial work on the failure path:
//
// func write() (err error) {
// f, err := os.Create(path)
// if err != nil { return err }
// defer errx.OnError(&err, func() { os.Remove(path) }) // undo on failure
// defer f.Close()
// return marshal(f)
// }
func OnError(errp *error, cleanup func()) {
if errp != nil && *errp != nil && cleanup != nil {
cleanup()
}
}
// OnSuccess runs fn ONLY if *errp is nil when the function returns.
func OnSuccess(errp *error, fn func()) {
if errp != nil && *errp == nil && fn != nil {
fn()
}
}
// AppendSuppressed records extra as a secondary error on *errp without
// letting it mask the primary. If *errp is nil, extra becomes the error;
// if *errp is an *Error, extra is attached via Suppress; otherwise the
// pair is joined.
func AppendSuppressed(errp *error, extra error) {
if errp == nil || extra == nil {
return
}
if *errp == nil {
*errp = extra
} else {
var e *Error
if errors.As(*errp, &e) {
_ = e.Suppress(extra) // builder return; mutation is the effect
} else {
*errp = Join(*errp, extra)
}
}
}
// CloseSuppressing closes c and folds any close error into *errp as a
// SECONDARY error, so a failing Close never masks the real failure (the
// classic `defer f.Close()` bug Go has no stdlib remedy for):
//
// defer errx.CloseSuppressing(&err, f)
func CloseSuppressing(errp *error, c io.Closer) {
if c == nil {
return
}
if cerr := c.Close(); cerr != nil {
AppendSuppressed(errp, cerr)
}
}