Skip to content

Commit

Permalink
feat: OnError - do a side effect
Browse files Browse the repository at this point in the history
  • Loading branch information
Primetalk committed Sep 5, 2022
1 parent d0201bf commit 57d93af
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -130,6 +130,7 @@ To construct an IO one may use the following functions:
- `io.Delay[A any](f func()IO[A]) IO[A]` - represents a function as a plain IO
- `io.Fold[A any, B any](io IO[A], f func(a A)IO[B], recover func (error)IO[B]) IO[B]` - handles both happy and sad paths.
- `io.Recover[A any](io IO[A], recover func(err error)IO[A])IO[A]` - handle only sad path and recover some errors to happy path.
- `io.OnError[A any](io IO[A], onError func(err error) IO[fun.Unit]) IO[A]` - OnError executes a side effect when there is an error.

### Manipulation

Expand Down
7 changes: 7 additions & 0 deletions io/io.go
Expand Up @@ -212,6 +212,13 @@ func Recover[A any](io IO[A], recover func(err error) IO[A]) IO[A] {
return Fold(io, Lift[A], recover)
}

// OnError executes a side effect when there is an error.
func OnError[A any](io IO[A], onError func(err error) IO[fun.Unit]) IO[A] {
return Fold(io, Lift[A], func(err error) IO[A] {
return AndThen(onError(err), Fail[A](err))
})
}

// Sequence takes a slice of IOs and returns an IO that will contain a slice of results.
// It'll fail if any of the internal computations fail.
func Sequence[A any](ioas []IO[A]) (res IO[[]A]) {
Expand Down
7 changes: 6 additions & 1 deletion io/io_test.go
Expand Up @@ -38,10 +38,15 @@ func TestFinally(t *testing.T) {
errorMessage := "on purpose failure"
failure := io.Fail[string](errors.New(errorMessage))
finalizerExecuted := false
onErrorExecuted := false
fin := io.Finally(failure, io.FromPureEffect(func() { finalizerExecuted = true }))
_, err := io.UnsafeRunSync(fin)
oe := io.OnError(fin, func(err error) io.IO[fun.Unit] {
return io.FromPureEffect(func() { onErrorExecuted = true })
})
_, err := io.UnsafeRunSync(oe)
assert.Error(t, err, errorMessage)
assert.True(t, finalizerExecuted)
assert.True(t, onErrorExecuted)
}

func Nats(count int) (ios []io.IO[int]) {
Expand Down

0 comments on commit 57d93af

Please sign in to comment.