Skip to content

Commit

Permalink
feat: add Into and Must generic helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed May 30, 2022
1 parent bef5a9b commit e6c2115
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 0 deletions.
20 changes: 20 additions & 0 deletions example_Into_test.go
@@ -0,0 +1,20 @@
package errors_test

import (
"fmt"
"os"

"github.com/go-faster/errors"
)

func ExampleInto() {
_, err := os.Open("non-existing")
if err != nil {
if pathError, ok := errors.Into[*os.PathError](err); ok {
fmt.Println("Failed at path:", pathError.Path)
}
}

// Output:
// Failed at path: non-existing
}
17 changes: 17 additions & 0 deletions example_Must_test.go
@@ -0,0 +1,17 @@
package errors_test

import (
"fmt"
"regexp"

"github.com/go-faster/errors"
)

func ExampleMust() {
// Same as regexp.MustCompile, but generic.
r := errors.Must(regexp.Compile(`\d+`))
fmt.Println(r.String())

// Output:
// \d+
}
9 changes: 9 additions & 0 deletions into.go
@@ -0,0 +1,9 @@
package errors

// Into finds the first error in err's chain that matches target type T, and if so, returns it.
//
// Into is type-safe alternative to As.
func Into[T error](err error) (val T, ok bool) {
ok = As(err, &val)
return val, ok
}
10 changes: 10 additions & 0 deletions must.go
@@ -0,0 +1,10 @@
package errors

// Must is a generic helper, like template.Must, that wraps a call to a function returning (T, error)
// and panics if the error is non-nil.
func Must[T any](val T, err error) T {
if err != nil {
panic(err)
}
return val
}
24 changes: 24 additions & 0 deletions must_test.go
@@ -0,0 +1,24 @@
package errors

import (
"testing"
)

func TestMust(t *testing.T) {
if got := Must(10, nil); got != 10 {
t.Fatalf("Expected %+v, got %+v", 10, got)
}

panics := func() (r bool) {
defer func() {
if recover() != nil {
r = true
}
}()
Must(10, New("test error"))
return r
}()
if !panics {
t.Fatal("Panic expected")
}
}

0 comments on commit e6c2115

Please sign in to comment.