-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
A-yon Lee
committed
Jan 1, 2025
1 parent
76359cb
commit a81b61e
Showing
2 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package result_test | ||
|
||
import ( | ||
"fmt" | ||
"strconv" | ||
|
||
"github.com/ayonli/goext/result" | ||
) | ||
|
||
func ExampleWrap() { | ||
mathAdd := 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)) | ||
return num1 + num2, nil | ||
}) | ||
} | ||
|
||
res, err := mathAdd("10", "20") | ||
if err != nil { | ||
fmt.Println(err) | ||
} else { | ||
fmt.Println(res) | ||
} | ||
// Output: | ||
// 30 | ||
} | ||
|
||
func ExampleUnwrap() { | ||
mathAdd := 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)) | ||
return num1 + num2, nil | ||
}) | ||
} | ||
|
||
res, err := mathAdd("10", "20") | ||
if err != nil { | ||
fmt.Println(err) | ||
} else { | ||
fmt.Println(res) | ||
} | ||
// Output: | ||
// 30 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
package result | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
) | ||
|
||
func Wrap[R any](fn func() (value R, err error)) (value R, err error) { | ||
defer func() { | ||
if re := recover(); re != nil { | ||
if _err, ok := re.(error); ok { | ||
err = _err | ||
} else if str, ok := re.(string); ok { | ||
err = errors.New(str) | ||
} else { | ||
err = errors.New(fmt.Sprint(re)) | ||
} | ||
} | ||
}() | ||
|
||
return fn() | ||
} | ||
|
||
func Unwrap[R any](value R, err error) R { | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
return value | ||
} |