3

The following schema contains not null field in an object that is optional (the entire object is allowed to be null). It defines a list of Parent objects that have optional field Child - some Parents are allowed to have null Child.

type People {
people : [Parent]
}

type Parent {
child : Child
}

type Child {
key : String!
}

The following GraphQL query returns an expected list of Parent objects (some with null Child values). But it also returns an error attached to the result. Is this a bug in GraphQL (Child is optional)? Or is it expected behaviour?

Cannot return null for non-nullable type: 'String' within parent 'Child'
louisfischer
  • 1,968
  • 2
  • 20
  • 38

1 Answers1

4

This is expected behavior. The issue is not that some child field is null, but that some Child is returning null for key -- that's the String that's referred to in the error. You won't see the null key in your data; instead, the offending child field will just return null instead. That's because GraphQL errors are "bubbled up" to the next nullable parent field, as described in the spec:

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.

Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • Thanks! I guess that is the reason why GraphQL allows `null` in arrays as in https://stackoverflow.com/questions/46770501/graphql-non-nullable-array-list? – Vladimir Alexiev Jun 18 '19 at 13:34