Skip to content

Commit b4bb246

Browse files
authored
Merge pull request #4 from eleniums/feat/handle-error
Add method for handling errors from an error channel
2 parents 24918dd + a1b654a commit b4bb246

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

async.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,3 +114,14 @@ func Wait(errc <-chan error) error {
114114

115115
return nil
116116
}
117+
118+
// HandleError sets a handler function to be called anytime an error is received on the given channel.
119+
func HandleError(errc <-chan error, handler func(error)) {
120+
go func() {
121+
for err := range errc {
122+
if err != nil {
123+
handler(err)
124+
}
125+
}
126+
}()
127+
}

async_test.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package async
33
import (
44
"context"
55
"errors"
6+
"sync"
67
"sync/atomic"
78
"testing"
89
"time"
@@ -224,3 +225,36 @@ func Test_RunForever_Error(t *testing.T) {
224225
assert.Error(t, err)
225226
assert.True(t, count >= 10)
226227
}
228+
229+
func Test_HandleError_Success(t *testing.T) {
230+
// arrange
231+
var wg sync.WaitGroup
232+
wg.Add(3)
233+
234+
task1 := func() error {
235+
return errors.New("task1 error")
236+
}
237+
238+
task2 := func() error {
239+
time.Sleep(time.Millisecond * 200)
240+
return errors.New("task2 error")
241+
}
242+
243+
task3 := func() error {
244+
time.Sleep(time.Millisecond * 100)
245+
return errors.New("task3 error")
246+
}
247+
248+
// act
249+
errc := Run(task1, task2, task3)
250+
251+
count := 0
252+
HandleError(errc, func(err error) {
253+
defer wg.Done()
254+
count++
255+
})
256+
wg.Wait()
257+
258+
// assert
259+
assert.Equal(t, 3, count)
260+
}

0 commit comments

Comments
 (0)