File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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+ }
Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ package async
33import (
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+ }
You can’t perform that action at this time.
0 commit comments