Skip to content

Commit

Permalink
feat: add TryPanic
Browse files Browse the repository at this point in the history
  • Loading branch information
andeya committed Sep 20, 2022
1 parent 1300a93 commit 246f8ab
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
12 changes: 12 additions & 0 deletions errable.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ func ToErrable[E any](errVal E) Errable[E] {
return Errable[E]{errVal: &errVal}
}

// TryPanic panics if the errVal is not nil.
func TryPanic[E any](errVal E) {
ToErrable(errVal).TryPanic()
}

func (e Errable[E]) IsErr() bool {
return e.errVal != nil
}
Expand Down Expand Up @@ -83,6 +88,13 @@ func (e Errable[E]) CtrlFlow() CtrlFlow[E, Void] {
return Continue[E, Void](nil)
}

// TryPanic panics if the errVal is not nil.
func (e Errable[E]) TryPanic() {
if e.IsErr() {
panic(e.UnwrapErr())
}
}

type errorWithVal struct {
val any
}
Expand Down
5 changes: 5 additions & 0 deletions errable_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gust_test

import (
"errors"
"fmt"
"testing"

Expand All @@ -17,6 +18,10 @@ func TestErrable(t *testing.T) {

assert.False(t, gust.ToErrable[*int](nil).IsErr())
assert.False(t, gust.NonErrable[*int]().IsErr())

assert.True(t, gust.ToErrable[any](1).IsErr())
assert.True(t, gust.ToErrable[error](fmt.Errorf("")).IsErr())
assert.PanicsWithError(t, "test TryPanic", gust.ToErrable[error](errors.New("test TryPanic")).TryPanic)
}

func ExampleErrable() {
Expand Down

0 comments on commit 246f8ab

Please sign in to comment.