Skip to content

Commit fa67b69

Browse files
authored
Merge pull request #19 from tdakkota/feat/add-into-and-must
feat: add Into and Must generic helpers
2 parents 01fe582 + b53f5de commit fa67b69

File tree

6 files changed

+80
-1
lines changed

6 files changed

+80
-1
lines changed

example_Into_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package errors_test
2+
3+
import (
4+
"fmt"
5+
"os"
6+
7+
"github.com/go-faster/errors"
8+
)
9+
10+
func ExampleInto() {
11+
_, err := os.Open("non-existing")
12+
if err != nil {
13+
if pathError, ok := errors.Into[*os.PathError](err); ok {
14+
fmt.Println("Failed at path:", pathError.Path)
15+
}
16+
}
17+
18+
// Output:
19+
// Failed at path: non-existing
20+
}

example_Must_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package errors_test
2+
3+
import (
4+
"fmt"
5+
"net/url"
6+
7+
"github.com/go-faster/errors"
8+
)
9+
10+
func ExampleMust() {
11+
r := errors.Must(url.Parse(`https://google.com`))
12+
fmt.Println(r.String())
13+
14+
// Output:
15+
// https://google.com
16+
}

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module github.com/go-faster/errors
22

3-
go 1.17
3+
go 1.18

into.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package errors
2+
3+
// Into finds the first error in err's chain that matches target type T, and if so, returns it.
4+
//
5+
// Into is type-safe alternative to As.
6+
func Into[T error](err error) (val T, ok bool) {
7+
ok = As(err, &val)
8+
return val, ok
9+
}

must.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package errors
2+
3+
// Must is a generic helper, like template.Must, that wraps a call to a function returning (T, error)
4+
// and panics if the error is non-nil.
5+
func Must[T any](val T, err error) T {
6+
if err != nil {
7+
panic(err)
8+
}
9+
return val
10+
}

must_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package errors
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestMust(t *testing.T) {
8+
if got := Must(10, nil); got != 10 {
9+
t.Fatalf("Expected %+v, got %+v", 10, got)
10+
}
11+
12+
panics := func() (r bool) {
13+
defer func() {
14+
if recover() != nil {
15+
r = true
16+
}
17+
}()
18+
Must(10, New("test error"))
19+
return r
20+
}()
21+
if !panics {
22+
t.Fatal("Panic expected")
23+
}
24+
}

0 commit comments

Comments
 (0)