I'm using AppSync and DynamoDB. Is there a way to suppress the non-null error and return partial data for a graphql query whose result omits a non-null field? For example if I run the following query:
query GetPerson {
getPerson(id: "123") {
name
active
}
}
And in my AppSync resolver I have logic that decides whether or not to return the value for active
. If I decide not to return active
, then I get the following response:
{
"data": {
"getPerson": null
},
"errors": [
{
"path": [
"getPerson",
"active"
],
"locations": null,
"message": "Cannot return null for non-nullable type: 'Boolean' within parent 'Person' (/getPerson/active)"
}
]
}
because in my schema the active
field is non-null. Is there any to suppress this error and return the partial data (i.e. the value for name
)? I would like to get a response like this instead:
{
"data": {
"getPerson": {
"name": "Jane Doe"
}
},
"errors": [
{
"path": [
"getPerson",
"active"
],
"locations": null,
"message": "Cannot return null for non-nullable type: 'Boolean' within parent 'Person' (/getPerson/active)"
}
]
}
No. A non-null field should never return null.
If the field is requested and it resolves to null, GraphQL will return an error. Because the field cannot be null, GraphQL will return null for the parent field instead. If that field is also non-null, it will return null for that field's parent... and so on, until it hits either a nullable parent field or the root (i.e. data
). This behavior is described in the spec:
If an error is thrown while resolving a field, it should be treated as though the field returned null, and an error must be added to the "errors" list in the response.
If the result of resolving a field is null (either because the function to resolve the field returned null or because an error occurred), and that field is of a Non-Null type, then a field error is thrown. The error must be added to the "errors" list in the response...
Since Non-Null type fields cannot be null, field errors are propagated to be handled by the parent field. If the parent field may be null then it resolves to null, otherwise if it is a Non-Null type, the field error is further propagated to it’s parent field...
If all fields from the root of the request to the source of the field error return Non-Null types, then the "data" entry in the response should be null.
If it's possible for active
to be null, then you should not make it non-nullable in your schema.