-
Notifications
You must be signed in to change notification settings - Fork 0
/
errorhelper.go
68 lines (61 loc) · 1.46 KB
/
errorhelper.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
63
64
65
66
67
68
package errorhelper
import (
"fmt"
"path"
"strings"
"github.com/solsw/runtimehelper"
)
// UnwrapErrors returns the result of calling the [Unwrap] method on 'err', if err's
// type contains an [Unwrap] method returning []error.
// Otherwise or if the [Unwrap] method returns error, UnwrapErrors returns nil.
//
// [Unwrap]: https://pkg.go.dev/errors#pkg-overview
func UnwrapErrors(err error) []error {
u, ok := err.(interface {
Unwrap() []error
})
if !ok {
return nil
}
return u.Unwrap()
}
// Must0 [panics] with 'err', if 'err' is not nil.
//
// [panics]: https://pkg.go.dev/builtin#panic
func Must0(err error) {
if err != nil {
panic(err)
}
}
// Must returns 'r' if 'err' is nil. Otherwise, it [panics] with 'err'.
//
// [panics]: https://pkg.go.dev/builtin#panic
func Must[R any](r R, err error) R {
if err != nil {
panic(err)
}
return r
}
// Must2 returns ('r1', 'r2') if 'err' is nil. Otherwise, it [panics] with 'err'.
//
// [panics]: https://pkg.go.dev/builtin#panic
func Must2[R1, R2 any](r1 R1, r2 R2, err error) (R1, R2) {
if err != nil {
panic(err)
}
return r1, r2
}
// CallerError prepends the provided error (if not nil) with caller function name.
// If 'err' is nil, nil is returned.
func CallerError(err error) error {
if err == nil {
return nil
}
s1 := path.Base(runtimehelper.NthCallerName(2))
if s1 == "" {
return err
}
s2, _, _ := strings.Cut(s1, "[")
ss3 := strings.Split(s2, ".")
return fmt.Errorf("%s: %w", ss3[len(ss3)-1], err)
}