Add variation of panicWrap that does not take in a context
This commit is contained in:
parent
1133e261bf
commit
dc7c7b5c73
17
util.go
17
util.go
@ -19,7 +19,22 @@ func defaul[T comparable](value, def T) T {
|
|||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
func panicWrap(ctx context.Context, f func (context.Context) error) (err error) {
|
func panicWrap(f func() error) (err error) {
|
||||||
|
defer func () {
|
||||||
|
if pan := recover(); pan != nil {
|
||||||
|
if panErr, ok := pan.(error); ok {
|
||||||
|
err = panErr
|
||||||
|
} else {
|
||||||
|
err = errors.New(fmt.Sprint(pan))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} ()
|
||||||
|
|
||||||
|
err = f()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func panicWrapCtx(ctx context.Context, f func(context.Context) error) (err error) {
|
||||||
defer func () {
|
defer func () {
|
||||||
if pan := recover(); pan != nil {
|
if pan := recover(); pan != nil {
|
||||||
if panErr, ok := pan.(error); ok {
|
if panErr, ok := pan.(error); ok {
|
||||||
|
18
util_test.go
18
util_test.go
@ -17,6 +17,24 @@ func TestDefaul(test *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPanicWrap(test *testing.T) {
|
func TestPanicWrap(test *testing.T) {
|
||||||
|
err := panicWrap(func (ctx context.Context) error {
|
||||||
|
return errors.New("test case 0")
|
||||||
|
})
|
||||||
|
test.Log(err)
|
||||||
|
if err.Error() != "test case 0" { test.Fatal("not equal") }
|
||||||
|
err = panicWrap(func (ctx context.Context) error {
|
||||||
|
panic(errors.New("test case 1"))
|
||||||
|
})
|
||||||
|
test.Log(err)
|
||||||
|
if err.Error() != "test case 1" { test.Fatal("not equal") }
|
||||||
|
err = panicWrap( func (ctx context.Context) error {
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
test.Log(err)
|
||||||
|
if err != nil { test.Fatal("not equal") }
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPanicWrapCtx(test *testing.T) {
|
||||||
err := panicWrap(context.Background(), func (ctx context.Context) error {
|
err := panicWrap(context.Background(), func (ctx context.Context) error {
|
||||||
return errors.New("test case 0")
|
return errors.New("test case 0")
|
||||||
})
|
})
|
||||||
|
Loading…
Reference in New Issue
Block a user