-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathdo.go
More file actions
22 lines (20 loc) · 567 Bytes
/
do.go
File metadata and controls
22 lines (20 loc) · 567 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package mo
import (
"errors"
"fmt"
)
// Do executes a function within a monadic context, capturing any errors that occur.
// If the function executes successfully, its result is wrapped in a successful Result.
// If the function panics (indicating a failure), the panic is caught and converted into an error Result.
func Do[T any](fn func() T) (result Result[T]) {
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
result = Err[T](err)
} else {
result = Err[T](errors.New(fmt.Sprint(r)))
}
}
}()
return Ok(fn())
}