Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add Into and Must generic helpers #19

Merged
merged 2 commits into from May 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
}
16 changes: 16 additions & 0 deletions example_Must_test.go
@@ -0,0 +1,16 @@
package errors_test

import (
"fmt"
"net/url"

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

func ExampleMust() {
r := errors.Must(url.Parse(`https://google.com`))
fmt.Println(r.String())

// Output:
// https://google.com
}
2 changes: 1 addition & 1 deletion go.mod
@@ -1,3 +1,3 @@
module github.com/go-faster/errors

go 1.17
go 1.18
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")
}
}