Skip to content

Commit bf68c1b

Browse files
authored
Merge pull request #434 from fishy/fix-data-race
Add Result.AppendErrors
2 parents d902887 + 9f66740 commit bf68c1b

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

executor.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ func Execute(p ExecuteParams) (result *Result) {
3636
go func(out chan<- *Result, done <-chan struct{}) {
3737
defer func() {
3838
if err := recover(); err != nil {
39-
result.Errors = append(result.Errors, gqlerrors.FormatError(err.(error)))
39+
result.AppendErrors(gqlerrors.FormatError(err.(error)))
4040
}
4141
select {
4242
case out <- result:
@@ -54,7 +54,7 @@ func Execute(p ExecuteParams) (result *Result) {
5454
})
5555

5656
if err != nil {
57-
result.Errors = append(result.Errors, gqlerrors.FormatError(err))
57+
result.AppendErrors(gqlerrors.FormatError(err))
5858
return
5959
}
6060

@@ -67,7 +67,7 @@ func Execute(p ExecuteParams) (result *Result) {
6767

6868
select {
6969
case <-ctx.Done():
70-
result.Errors = append(result.Errors, gqlerrors.FormatError(ctx.Err()))
70+
result.AppendErrors(gqlerrors.FormatError(ctx.Err()))
7171
case r := <-resultChannel:
7272
result = r
7373
}

types.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package graphql
22

33
import (
4+
"sync"
5+
46
"github.com/graphql-go/graphql/gqlerrors"
57
)
68

@@ -9,8 +11,18 @@ import (
911
type Result struct {
1012
Data interface{} `json:"data"`
1113
Errors []gqlerrors.FormattedError `json:"errors,omitempty"`
14+
15+
errorsLock sync.Mutex
1216
}
1317

1418
func (r *Result) HasErrors() bool {
1519
return len(r.Errors) > 0
1620
}
21+
22+
// AppendErrors is the thread-safe way to append error(s) to Result.Errors.
23+
func (r *Result) AppendErrors(errs ...gqlerrors.FormattedError) {
24+
r.errorsLock.Lock()
25+
defer r.errorsLock.Unlock()
26+
27+
r.Errors = append(r.Errors, errs...)
28+
}

0 commit comments

Comments
 (0)