Skip to content

Commit 35fec87

Browse files
authored
add try with pass thru of error (#25)
1 parent c88b521 commit 35fec87

File tree

1 file changed

+39
-9
lines changed

1 file changed

+39
-9
lines changed

must/must.go

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,24 @@ import (
77
)
88

99
type Error struct {
10-
Ctx context.Context
11-
Stack []byte
12-
error
10+
Ctx context.Context
11+
Stack []byte
12+
wrapped error
1313
}
1414

15-
func mkErr(ctx context.Context, err error) Error {
16-
return Error{Ctx: ctx, Stack: debug.Stack(), error: err}
15+
func (x *Error) Error() string {
16+
return x.Wrapped().Error()
17+
}
18+
19+
func (x *Error) Wrapped() error {
20+
if x == nil {
21+
return nil
22+
}
23+
return x.wrapped
24+
}
25+
26+
func mkErr(ctx context.Context, wrapped error) *Error {
27+
return &Error{Ctx: ctx, Stack: debug.Stack(), wrapped: wrapped}
1728
}
1829

1930
func Panic(ctx context.Context, err error) {
@@ -47,7 +58,17 @@ func NoError(ctx context.Context, err error) {
4758
func Try(f func()) (err error) {
4859
defer func() {
4960
if r := recover(); r != nil {
50-
err = r.(Error).error
61+
err = r.(*Error).Wrapped()
62+
}
63+
}()
64+
f()
65+
return nil
66+
}
67+
68+
func TryThru(f func()) (err *Error) {
69+
defer func() {
70+
if r := recover(); r != nil {
71+
err = r.(*Error)
5172
}
5273
}()
5374
f()
@@ -57,8 +78,8 @@ func Try(f func()) (err error) {
5778
func TryWithStack(f func()) (err error, stack []byte) {
5879
defer func() {
5980
if r := recover(); r != nil {
60-
err = r.(Error).error
61-
stack = r.(Error).Stack
81+
err = r.(*Error).Wrapped()
82+
stack = r.(*Error).Stack
6283
}
6384
}()
6485
f()
@@ -68,7 +89,16 @@ func TryWithStack(f func()) (err error, stack []byte) {
6889
func Try1[R1 any](f func() R1) (_ R1, err error) {
6990
defer func() {
7091
if r := recover(); r != nil {
71-
err = r.(Error).error
92+
err = r.(*Error).Wrapped()
93+
}
94+
}()
95+
return f(), nil
96+
}
97+
98+
func Try1Thru[R1 any](f func() R1) (_ R1, err *Error) {
99+
defer func() {
100+
if r := recover(); r != nil {
101+
err = r.(*Error)
72102
}
73103
}()
74104
return f(), nil

0 commit comments

Comments
 (0)