Errors
A response can carry errors next to its data. This page shows which errors reach the response and how, how to give clients a machine-readable error code, how to reach the error a resolver returned, and how to keep internal details out of responses; the complete program is at the end.
Request errors and field errors
| Error | When | data | path |
|---|---|---|---|
| Syntax | The document does not parse. | null | none |
| Validation | The document does not fit the schema. | null | none |
| Variables | A variable is missing or invalid. | null | none |
| Field | A resolver returned an error or panicked, or a value could not be completed. | the rest of the data | the field’s path |
A request error stops the request before any resolver runs. A field error makes
its field null and leaves the other fields alone; when the field is non-null,
the null moves up to the nearest nullable parent, as described in
Lists and non-null.
When that happens, the fields of the same parent that come after the failing
one are not resolved, and their errors are not reported
(#126).
FormattedError
result.Errors is a slice of gqlerrors.FormattedError, which encodes to the
error format of the specification:
| Field | JSON | Content |
|---|---|---|
Message | message | The error’s message. |
Locations | locations | Where in the document the error is, as line and column. An empty list for errors without a location, such as an unknown operation name. |
Path | path | For a field error, the response keys and list indexes that lead to the field. Omitted otherwise. |
Extensions | extensions | Extra data for clients, such as an error code. Omitted when empty. |
Message and Locations can be changed before the result is sent, which is how
masking works.
Error codes with extensions
An error that implements gqlerrors.ExtendedError, by having an
Extensions() map[string]interface{} method, adds those values to the error’s
extensions in the response. Clients can then act on a code instead of parsing
messages:
// CodedError is an error meant for clients. Its code appears in the
// response's extensions, because it implements gqlerrors.ExtendedError.
type CodedError struct {
Code string
Message string
}
func (e *CodedError) Error() string { return e.Message }
func (e *CodedError) Extensions() map[string]interface{} {
return map[string]interface{}{"code": e.Code}
}{
"message": "no such book",
"locations": [{ "line": 3, "column": 3 }],
"path": ["missing"],
"extensions": { "code": "NOT_FOUND" }
}This works for an error returned by a resolver and for one a resolver panics
with. The extensions are lost when the error is wrapped, for example with
fmt.Errorf("loading: %w", err), and on a few other paths
(#62): return the
ExtendedError itself. A hook to present every error in one place is on the
roadmap (#14).
Reaching the original error
result.ErrorsJoined() (v0.12.0) joins the errors into one error whose
chain reaches the errors the resolvers returned, so errors.Is and errors.As
work across the whole response:
fmt.Println("database down:", errors.Is(result.ErrorsJoined(), errDatabase))For a single error, OriginalError() returns the located error that wraps the
resolver’s error, a *gqlerrors.Error; its OriginalError field holds the error
the resolver returned:
// cause returns the error a resolver returned for a field error, unwrapping
// the layers the executor adds around it, or the error itself for others.
func cause(e gqlerrors.FormattedError) error {
err := e.OriginalError()
for {
switch layer := err.(type) {
case *gqlerrors.Error:
if layer.OriginalError == nil {
return err
}
err = layer.OriginalError
case gqlerrors.FormattedError:
if layer.OriginalError() == nil {
return err
}
err = layer.OriginalError()
default:
return err
}
}
}Masking internal errors
The message of an error a resolver returns, or of a runtime panic such as a nil map assignment, goes to the client as it is, and can reveal internal details. Until there is a hook for it (#14, #73), rewrite the errors after execution and before writing the response:
// maskInternal rewrites the errors of a result before it is sent. A client
// error keeps only its own message and code; an error in the client's
// document is kept; every other error becomes "internal error", without
// extensions, after being logged.
func maskInternal(result *graphql.Result) {
for i, e := range result.Errors {
var coded *CodedError
switch {
case errors.As(cause(e), &coded):
// Drop the messages of any errors that wrap it.
result.Errors[i].Message = coded.Message
result.Errors[i].Extensions = coded.Extensions()
case isDocumentError(e):
// Kept: it describes the client's document.
default:
log.Printf("internal error at %v: %v", e.Path, e.Message)
result.Errors[i].Message = "internal error"
result.Errors[i].Extensions = nil
}
}
}The helper applies three rules:
Client errors keep only the
CodedError’s own message and code. When a resolver wraps one, for examplefmt.Errorf("query reviews on replica-3: %w", err), the wrapper’s message is dropped and the code, which wrapping would otherwise lose, is restored.Errors in the client’s document (syntax, validation and variable errors) are kept. The library raises them without wrapping another error, while an error from a resolver wraps the error it returned, even one built with
graphql.NewLocatedError; that tells them apart more reliably than a missing path. The exception is a resolver that builds agqlerrors.Errorwithout an original error itself, which this check keeps, so do not build internal errors that way:// isDocumentError reports whether the library raised e for the client's // document: a syntax, validation or variable error, which wraps no other // error. Errors from resolvers wrap the error they returned, unless a resolver // builds a gqlerrors.Error without one itself. func isDocumentError(e gqlerrors.FormattedError) bool { located, ok := e.OriginalError().(*gqlerrors.Error) return ok && located.OriginalError == nil }Everything else becomes
internal error, without extensions, and the real message goes to your logs. That includes errors such as a cancelled context or a panic in an extension’s hook, and also the operation selection errors (Unknown operation named "C".), which the library returns as plain errors that cannot be told apart from internal ones. To give clients those messages, checkOperationNameagainst the document’s operations before callinggraphql.Do.
Building errors
gqlerrors.NewFormattedError(message) makes a FormattedError from a message,
and gqlerrors.FormatError(err) and gqlerrors.FormatErrors(errs...) convert Go
errors, which is useful when your own code, such as an HTTP handler, needs to
answer with errors in the same format.
Complete program
main.go
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"github.com/gql-go/graphql"
"github.com/gql-go/graphql/gqlerrors"
)
// CodedError is an error meant for clients. Its code appears in the
// response's extensions, because it implements gqlerrors.ExtendedError.
type CodedError struct {
Code string
Message string
}
func (e *CodedError) Error() string { return e.Message }
func (e *CodedError) Extensions() map[string]interface{} {
return map[string]interface{}{"code": e.Code}
}
var errDatabase = errors.New("connection refused: db:5432")
var books = map[string]string{"1": "A Wizard of Earthsea"}
func newSchema() (graphql.Schema, error) {
bookType := graphql.NewObject(graphql.ObjectConfig{
Name: "Book",
Fields: graphql.Fields{
"title": &graphql.Field{Type: graphql.String},
"sales": &graphql.Field{
Type: graphql.Int,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return nil, &CodedError{Code: "FORBIDDEN", Message: "sales are private"}
},
},
},
})
queryType := graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"book": &graphql.Field{
Type: bookType,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{Type: graphql.NewNonNull(graphql.ID)},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
title, ok := books[p.Args["id"].(string)]
if !ok {
return nil, &CodedError{Code: "NOT_FOUND", Message: "no such book"}
}
return map[string]interface{}{"title": title}, nil
},
},
"reviews": &graphql.Field{
Type: graphql.NewList(graphql.String),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
err := &CodedError{Code: "UNAVAILABLE", Message: "reviews are unavailable"}
return nil, fmt.Errorf("query reviews on replica-3: %w", err)
},
},
"stock": &graphql.Field{
Type: graphql.Int,
// A concurrent resolver: the error comes from the returned
// function.
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return func() (interface{}, error) {
return nil, &CodedError{Code: "UNAVAILABLE", Message: "stock is unavailable"}
}, nil
},
},
"bestsellers": &graphql.Field{
Type: graphql.NewList(graphql.String),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return nil, fmt.Errorf("loading bestsellers: %w", errDatabase)
},
},
},
})
return graphql.NewSchema(graphql.SchemaConfig{Query: queryType})
}
// cause returns the error a resolver returned for a field error, unwrapping
// the layers the executor adds around it, or the error itself for others.
func cause(e gqlerrors.FormattedError) error {
err := e.OriginalError()
for {
switch layer := err.(type) {
case *gqlerrors.Error:
if layer.OriginalError == nil {
return err
}
err = layer.OriginalError
case gqlerrors.FormattedError:
if layer.OriginalError() == nil {
return err
}
err = layer.OriginalError()
default:
return err
}
}
}
// isDocumentError reports whether the library raised e for the client's
// document: a syntax, validation or variable error, which wraps no other
// error. Errors from resolvers wrap the error they returned, unless a resolver
// builds a gqlerrors.Error without one itself.
func isDocumentError(e gqlerrors.FormattedError) bool {
located, ok := e.OriginalError().(*gqlerrors.Error)
return ok && located.OriginalError == nil
}
// maskInternal rewrites the errors of a result before it is sent. A client
// error keeps only its own message and code; an error in the client's
// document is kept; every other error becomes "internal error", without
// extensions, after being logged.
func maskInternal(result *graphql.Result) {
for i, e := range result.Errors {
var coded *CodedError
switch {
case errors.As(cause(e), &coded):
// Drop the messages of any errors that wrap it.
result.Errors[i].Message = coded.Message
result.Errors[i].Extensions = coded.Extensions()
case isDocumentError(e):
// Kept: it describes the client's document.
default:
log.Printf("internal error at %v: %v", e.Path, e.Message)
result.Errors[i].Message = "internal error"
result.Errors[i].Extensions = nil
}
}
}
func main() {
log.SetFlags(0)
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
query := `{
found: book(id: "1") { title sales }
missing: book(id: "9") { title }
reviews
stock
bestsellers
}`
result := graphql.Do(graphql.Params{Schema: schema, RequestString: query})
// ErrorsJoined reaches the errors the resolvers returned.
fmt.Println("database down:", errors.Is(result.ErrorsJoined(), errDatabase))
maskInternal(result)
out, _ := json.MarshalIndent(result, "", " ")
fmt.Println(string(out))
}Running it logs the masked error:
internal error at [bestsellers]: loading bestsellers: connection refused: db:5432and prints:
database down: true
{
"data": {
"bestsellers": null,
"found": {
"sales": null,
"title": "A Wizard of Earthsea"
},
"missing": null,
"reviews": null,
"stock": null
},
"errors": [
{
"message": "sales are private",
"locations": [
{
"line": 2,
"column": 32
}
],
"path": [
"found",
"sales"
],
"extensions": {
"code": "FORBIDDEN"
}
},
{
"message": "no such book",
"locations": [
{
"line": 3,
"column": 3
}
],
"path": [
"missing"
],
"extensions": {
"code": "NOT_FOUND"
}
},
{
"message": "reviews are unavailable",
"locations": [
{
"line": 4,
"column": 3
}
],
"path": [
"reviews"
],
"extensions": {
"code": "UNAVAILABLE"
}
},
{
"message": "internal error",
"locations": [
{
"line": 6,
"column": 3
}
],
"path": [
"bestsellers"
]
},
{
"message": "stock is unavailable",
"locations": [
{
"line": 5,
"column": 3
}
],
"path": [
"stock"
],
"extensions": {
"code": "UNAVAILABLE"
}
}
]
}