What is the purpose of GraphQL's non-null (!) type modifier, and what happens if a resolver for a non-null field returns null unexpectedly?
Short answer
Appending ! to a type (like String! or [Post!]!) declares that field as non-nullable, meaning the schema guarantees clients will always receive a value, never null -- if a resolver for a non-null field somehow returns null or throws an error, GraphQL's null-propagation behavior…
Advertisement
AModel answer
Appending ! to a type (like String! or [Post!]!) declares that field as non-nullable, meaning the schema guarantees clients will always receive a value, never null -- if a resolver for a non-null field somehow returns null or throws an error, GraphQL's null-propagation behavior bubbles that null upward to the nearest nullable ancestor field in the query, potentially nulling out an entire larger portion of the response (or the whole response, if there's no nullable ancestor at all) rather than allowing the type contract to be silently violated.
type Query { user(id: ID!): User! } # this field promises to always return a User, never null
# If the resolver for 'user' throws or returns null unexpectedly,
# GraphQL nulls out the nearest nullable ancestor -- potentially the entire
# 'data' field of the response if there's no nullable field above itReal-world example
A team debugging why an entire GraphQL response unexpectedly came back as null (with no data at all) traces it to a single deeply nested non-null field's resolver throwing an error, whose null then propagated all the way up through several non-null ancestor fields until it reached the top-level response itself.
Likely follow-ups
- Why does GraphQL's null-propagation behavior sometimes surprise developers coming from REST, where an error in one part of the response wouldn't invalidate the entire payload?
- How would you design a schema to minimize the blast radius of a single field's failure, using nullable types more strategically?
Related topics