Skip to content

Commit

Permalink
refine result package
Browse files Browse the repository at this point in the history
  • Loading branch information
ayuan.li committed Jan 2, 2025
1 parent 52d9e49 commit b606d6f
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require github.com/stretchr/testify v1.8.4

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
Expand Down
18 changes: 18 additions & 0 deletions result/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"

"github.com/ayonli/goext/result"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -47,6 +48,10 @@ func ExampleUnwrap() {
// 30
}

func withOtherError() (string, error) {
return "", errors.WithStack(errors.New("something went wrong"))
}

func TestWrap(t *testing.T) {
mathAdd := func(input1 string, input2 string) (int, error) {
return result.Wrap(func() (int, error) {
Expand All @@ -59,4 +64,17 @@ func TestWrap(t *testing.T) {
res, err := mathAdd("10", "b")
assert.Equal(t, 0, res)
assert.Equal(t, "strconv.Atoi: parsing \"b\": invalid syntax", err.Error())

mathAdd2 := func(input1 string, input2 string) (int, error) {
return result.Wrap(func() (int, error) {
num1 := result.Unwrap(strconv.Atoi(input1))
num2 := result.Unwrap(strconv.Atoi(input2))
result.Unwrap(withOtherError())
return num1 + num2, nil
})
}

_, err = mathAdd2("10", "20")
assert.Equal(t, "something went wrong", err.Error())
assert.Contains(t, fmt.Sprintf("%+v", err), "result_test.withOtherError")
}
2 changes: 1 addition & 1 deletion result/result.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func Wrap[T any](fn func() (value T, err error)) (value T, err error) {
return fn()
}

func Unwrap[R any](value R, err error) R {
func Unwrap[T any](value T, err error) T {
if err != nil {
panic(err)
}
Expand Down

0 comments on commit b606d6f

Please sign in to comment.