Join us from October 8-10 in New York City to learn the latest tips, trends, and news about GraphQL Federation and API platform engineering.Join us for GraphQL Summit 2024 in NYC
Docs
Start for Free
You're viewing documentation for an upcoming version of this software. Switch to the latest stable version.

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.

does not have a Result type. If a 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: String
avatarUrl: String
}

The GraphQL best practices recommend making 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 GetUser {
user {
id
name
avatarUrl
}
}

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:

@Composable
fun 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?

offers nullability 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 convenience
import: ["@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 .

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 error
name: 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 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 :

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 error
adminRoles: [AdminRole] @semanticNonNull(levels: [1])
}

With @semanticNonNull, a frontend developer knows that a given field will never be null in regular 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. file:

# Same effect as above but works as a schema extensions
extend 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 FieldResult
friends @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 parsing
name @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 error
println(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 error
name @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 null
name @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 schema
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 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 .)

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:

  1. import the nullability directives.
  2. Default to coercing to null: extend schema @catchByDefault(to: NULL). This is a no-op to start exploring the directives.
  3. Add @catch to individual fields, get more comfortable with how it works.
  4. When ready to do the big switch, change to extend schema catch(to: THROW) and (at the same time) add query GetFoo @catch(to: NULL) {} on all operations/ (this is a no-op).
  5. From this moment on, new queries written are catch(to: THROW) by default.
  6. Remove query GetFoo @catch(to: NULL) {} progressively.
Previous
Monitoring the network state
Next
Experimental WebSockets
Rate articleRateEdit on GitHubEditForumsDiscord

© 2024 Apollo Graph Inc., d/b/a Apollo GraphQL.

Privacy Policy

Company