If you mark a field as non-null (by appending !
to the type) and then resolve that field to null, GraphQL will always throw an error -- that's unavoidable. If it's possible for a field to end up null in the normal operation of your API, you should probably make it nullable.
However, errors "bubble up" to the nearest nullable field.
So given a schema like this:
type Query {
cars: [Car!]!
}
type Car {
registration: Registration!
}
and this query
{
cars {
registrations
}
}
resolving the registration
field for any one Car
to null
will result in the following because the cars
field is non-null and each individual Car
must also not be null
:
{
"data": null,
"errors": [...]
}
If you make the cars field nullable ([Car!]
), the error will stop there:
{
"data": {
"cars": null
},
"errors": [...]
}
However, you can make each Car
nullable (whether the field is or not), which will let the error stop there and result in an array of objects and nulls (the nulls being the cars that errored). So making the cars
type [Car]!
or [Car]
will give us:
{
"data": {
"cars": [{...}, {...}, null]
},
"errors": [...]
}