Skip to content

Commit

Permalink
Improve operation error handling (#2184)
Browse files Browse the repository at this point in the history
  • Loading branch information
Desuuuu committed May 23, 2022
1 parent 2526f68 commit 7c95938
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
11 changes: 10 additions & 1 deletion graphql/executor/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@ func (e *Executor) CreateOperationContext(ctx context.Context, params *graphql.R

rc.Operation = rc.Doc.Operations.ForName(params.OperationName)
if rc.Operation == nil {
return rc, gqlerror.List{gqlerror.Errorf("operation %s not found", params.OperationName)}
err := gqlerror.Errorf("operation %s not found", params.OperationName)
errcode.Set(err, errcode.ValidationFailed)
return rc, gqlerror.List{err}
}

var err *gqlerror.Error
Expand Down Expand Up @@ -178,6 +180,13 @@ func (e *Executor) parseQuery(ctx context.Context, stats *graphql.Stats, query s
stats.Parsing.End = graphql.Now()

stats.Validation.Start = graphql.Now()

if len(doc.Operations) == 0 {
err = gqlerror.Errorf("no operation provided")
errcode.Set(err, errcode.ValidationFailed)
return nil, gqlerror.List{err}
}

listErr := validator.Validate(e.es.Schema(), doc)
if len(listErr) != 0 {
for _, e := range listErr {
Expand Down
17 changes: 17 additions & 0 deletions graphql/executor/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"testing"

"github.com/99designs/gqlgen/graphql"
"github.com/99designs/gqlgen/graphql/errcode"
"github.com/99designs/gqlgen/graphql/executor/testexecutor"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -21,6 +22,22 @@ func TestExecutor(t *testing.T) {
assert.Equal(t, `{"name":"test"}`, string(resp.Data))
})

t.Run("validates operation", func(t *testing.T) {
t.Run("no operation", func(t *testing.T) {
resp := query(exec, "", "")
assert.Equal(t, "", string(resp.Data))
assert.Equal(t, 1, len(resp.Errors))
assert.Equal(t, errcode.ValidationFailed, resp.Errors[0].Extensions["code"])
})

t.Run("bad operation", func(t *testing.T) {
resp := query(exec, "badOp", "query test { name }")
assert.Equal(t, "", string(resp.Data))
assert.Equal(t, 1, len(resp.Errors))
assert.Equal(t, errcode.ValidationFailed, resp.Errors[0].Extensions["code"])
})
})

t.Run("invokes operation middleware in order", func(t *testing.T) {
var calls []string
exec.AroundOperations(func(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler {
Expand Down

0 comments on commit 7c95938

Please sign in to comment.