Handling nullability and errors
Make your queries even more typesafe
Nullability annotations are currently experimental in Apollo Kotlin. If you have feedback on them, please let us know via GitHub issues, in the Kotlin Slack community, or in the GraphQL nullability working group.
Introduction
This section is a high level description of nullability and errors in GraphQL and the problem it causes for app developers. For the proposed solution, skip directly to the @semanticNonNull section.
GraphQL does not have a Result
type. If a field errors, it is set to null
in the JSON response and an error is added to the errors
array.
From the schema alone, it is impossible to tell if null
is a valid business value or only happens for errors:
type User {id: ID!# Should the UI deal with user without a name here? It's impossible to tell.name: StringavatarUrl: String}
The GraphQL best practices recommend making fields nullable by default to account for errors.
From graphql.org:
In a GraphQL type system, every field is nullable by default. This is because there are many things that can go awry in a networked service backed by databases and other services.
For an example, the following query:
query GetUser {user {idnameavatarUrl}}
receives a response like so in the case of an error:
{"data": {"user": {"id": "1001","name": null,"avatarUrl": "https://example.com/pic.png"}},"errors": [{"message": "Cannot resolve user.name","path": ["user", "name"]}]}
This nullable default has one major drawback for frontend developers. It requires to carefully check every field in your UI code.
Sometimes it's not clear how to handle the different cases:
@Composablefun User(user: GetUserQuery.User) {if (user.name != null) {Text(text = user.name)} else {// What to do here?// Is it an error?// Is it a true null?// Should I display a placeholder? an error? hide the view?}}
When there are a lot of fields, handling the null
case on every one of them becomes really tedious.
Wouldn't it be nice if instead the UI could decide to handle errors more globally and display a general error if any field in an User
fails?
Apollo Kotlin offers nullability directives to deal with this situation:
These tools change the GraphQL default from "handle every field error" to "opt-in the errors you want to handle".
Import the nullability directives
Nullability directives are experimental. You need to import them using the @link
directive:
extend schema @link(url: "https://specs.apollo.dev/nullability/v0.4",# Note: other directives are needed later on and added here for convenienceimport: ["@semanticNonNull", "@semanticNonNullField", "@catch", "CatchTo", "@catchByDefault"])
ⓘ NOTE
You will also need to opt in a default catch but more on that later.
@semanticNonNull
@semanticNonNull
introduces a new type in the GraphQL type system.
A @semanticNonNull
type can never be null except if there is an error in the errors array.
Use it in your schema:
type User {id: ID!# name is never null unless there is an errorname: String @semanticNonNull# avatarUrl may be null even if there is no error. In that case the UI should be prepared to display a placeholder.avatarUrl: String}
ⓘ NOTE
@semanticNonNull
is a directive so that it can be introduced without breaking the current GraphQL tooling but the ultimate goal is to introduce new syntax. See the nullability working group discussion for more details.
For fields of List
type, @semanticNonNull
applies only to the first level. If you need to apply it to a given level, use the levels
argument:
type User {# adminRoles may be null if the user is not an admin# if the user is an admin, adminRoles[i] is never null unless there is also an erroradminRoles: [AdminRole] @semanticNonNull(levels: [1])}
With @semanticNonNull
, a frontend developer knows that a given field will never be null in regular operation and can therefore act accordingly. No need to guess anymore!
Ideally, your backend team annotates their schema with @semanticNonNull
directives so that different frontend teams can benefit from the new type information.
Sometimes this process takes time.
For these situations, you can extend your schema by using @semanticNonNullField
in your extra.graphqls file:
# Same effect as above but works as a schema extensionsextend type User @semanticNonNullField(name: "name")
You can later share that file with your backend team and double check that your interpretation of the types is the correct one.
@catch
While @semanticNonNull
is a server directive that describes your data, @catch
is a client directive that defines how to handle errors.
@catch
allows to:
- handle errors as
FieldResult<T>
, getting access to the colocated error. - throw the error and let another parent field handle it or bubble up to
data == null
. - coerce the error to
null
(current GraphQL default).
For fields of List
type, @catch
applies only to the first level. If you need to apply it to a given level, use the levels
argument:
query GetUser {user {# map friends[i] to FieldResultfriends @catch(to: RESULT, level: 1)}}
Colocate errors
To get colocated errors, use @catch(to: RESULT)
:
query GetUser {user {id# map name to FieldResult<String> instead of stopping parsingname @catch(to: RESULT)}}
The above query generates the following Kotlin code:
class User(val id: String,// note how String is not nullable. This is because name// was marked `@semanticNonNull` in the previous section.val name: FieldResult<String>,)
Use getOrNull()
to get the value:
println(user.name.getOrNull()) // "Luke Skywalker"// or you can also decide to throw on errorprintln(user.name.getOrThrow())
And graphQLErrorOrNull()
to get the colocated error:
println(user.name.graphQLErrorOrNull()) // "Cannot resolve user.name"
Throw errors
To throw errors, use @catch(to: THROW)
:
query GetUser {user {id# throw any errorname @catch(to: THROW)}}
The above query generates the following Kotlin code:
class User(val id: String,val name: String,)
ⓘ NOTE
The error is thrown during parsing but still caught before it reaches your UI code. If no parent field catches it, the Apollo Kotlin runtime will and set it as ApolloResponse.exception
.
Coerce errors to null
To coerce errors to null
(current GraphQL default), use @catch(to: NULL)
:
query GetUser {user {id# coerce errors to nullname @catch(to: NULL)}}
The above query generates the following Kotlin code:
class User(val id: String,// Note how name is nullable again despite being marked// @semanticNonNull in the schemaval name: String?,)
ⓘ NOTE
The error is thrown during parsing but still caught before it reaches your UI code. If no parent field catches it, the Apollo Kotlin runtime does and exposes the exception in ApolloResponse.exception
.
@catchByDefault
In order to use the nullability directives, you need to opt in a default catch behaviour for nullable GraphQL fields using @catchByDefault
.
You can choose to map nullable fields to FieldResult
:
# Errors stop the parsing.extend schema @catchByDefault(to: RESULT)
Or throw errors:
# Errors stop the parsing.extend schema @catchByDefault(to: THROW)
Or coerce errors to null
, like the current GraphQL default:
# Coerce errors to null by default.extend schema @catchByDefault(to: NULL)
(Adding @catchByDefault(to: NULL)
is a no-op for codegen that unlocks using @catch
in your operations.)
Migrate to semantic nullability
Semantic nullability is the most useful for schemas that are nullable by default. These are the schemas that require "handling every field error".
In order to change that default to "opt-in the errors you want to handle", you can use the following approach:
- import the nullability directives.
- Default to coercing to null:
extend schema @catchByDefault(to: NULL)
. This is a no-op to start exploring the directives. - Add
@catch
to individual fields, get more comfortable with how it works. - When ready to do the big switch, change to
extend schema catch(to: THROW)
and (at the same time) addquery GetFoo @catch(to: NULL) {}
on all operations/fragments (this is a no-op). - From this moment on, new queries written are
catch(to: THROW)
by default. - Remove
query GetFoo @catch(to: NULL) {}
progressively.