Skip to content

Commit

Permalink
Implements error methods (#6)
Browse files Browse the repository at this point in the history
* Implements Is(target error) method

* Implements As(target interface{}) method
  • Loading branch information
matsuyoshi30 authored Mar 7, 2022
1 parent 112d067 commit de40458
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
19 changes: 19 additions & 0 deletions semgroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package semgroup

import (
"context"
"errors"
"fmt"
"strings"
"sync"
Expand Down Expand Up @@ -98,3 +99,21 @@ func (e multiError) ErrorOrNil() error {

return e
}

func (e multiError) Is(target error) bool {
for _, err := range e {
if errors.Is(err, target) {
return true
}
}
return false
}

func (e multiError) As(target interface{}) bool {
for _, err := range e {
if errors.As(err, target) {
return true
}
}
return false
}
66 changes: 66 additions & 0 deletions semgroup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package semgroup
import (
"context"
"errors"
"os"
"sync"
"testing"
)
Expand Down Expand Up @@ -91,3 +92,68 @@ func TestGroup_deadlock(t *testing.T) {
t.Errorf("error should be:\n%s\ngot:\n%s\n", wantErr, err.Error())
}
}

func TestGroup_multiple_tasks_errors_Is(t *testing.T) {
ctx := context.Background()
g := NewGroup(ctx, 1)

var (
fooErr = errors.New("foo")
barErr = errors.New("bar")
bazErr = errors.New("baz")
)

g.Go(func() error { return fooErr })
g.Go(func() error { return nil })
g.Go(func() error { return barErr })
g.Go(func() error { return nil })

err := g.Wait()
if err == nil {
t.Fatalf("g.Wait() should return an error")
}

if !errors.Is(err, fooErr) {
t.Errorf("error should be contained %v\n", fooErr)
}

if !errors.Is(err, barErr) {
t.Errorf("error should be contained %v\n", barErr)
}

if errors.Is(err, bazErr) {
t.Errorf("error should not be contained %v\n", bazErr)
}
}

type foobarErr struct{ str string }

func (e foobarErr) Error() string {
return "foobar"
}

func TestGroup_multiple_tasks_errors_As(t *testing.T) {
ctx := context.Background()
g := NewGroup(ctx, 1)

g.Go(func() error { return foobarErr{"baz"} })
g.Go(func() error { return nil })

err := g.Wait()
if err == nil {
t.Fatalf("g.Wait() should return an error")
}

var (
fbe foobarErr
pe *os.PathError
)

if !errors.As(err, &fbe) {
t.Error("error should be matched foobarErr")
}

if errors.As(err, &pe) {
t.Error("error should not be matched os.PathError")
}
}

0 comments on commit de40458

Please sign in to comment.