Docs
Try Apollo Studio

Error Handling


Whenever you execute a GraphQL operation with two high-level types of errors can occur:

Network errors

The result of executing an operation is a Swift Result. A network error results in a .failure(Error) result for the operation.

You can handle network errors by using a do/catch block and calling try result.get() or by switching on the result.

apollo.fetch(query: HeroNameQuery()) { result in
do {
let data = try result.get().data
...
} catch {
// Network error
print(error)
}
}
apollo.fetch(query: HeroNameQuery()) { result in
switch result {
case .success(let response):
...
case .failure(let error):
// Network error
print(error)
}
}

Causes

Possible causes of a network error include (but are not limited to):

  • The app is offline or doesn't have access to the network.
  • A DNS error occurred, making it impossible to look up the host.
  • An SSL error occurred (e.g., the server certificate isn't trusted).
  • The connection was closed.
  • The server responded with a non-successful HTTP code.
  • The server didn't respond with valid JSON.
  • The response JSON doesn't satisfy the schema and cannot be parsed.
  • A request was specified as .returnCacheDataDontFetch but the data wasn't cached.

Examine the exception for more detailed information about the actual error.

GraphQL errors

Because a response with GraphQL errors might still contain data, a .failure result is not returned. Instead, they return a .success result containing a GraphQLResult whose errors field contains the errors that occurred.

For example, the following query uses an invalid id to look up a Person:

query FilmAndPersonQuery {
film(id: "ZmlsbXM6M") {
title
}
person(id: "badId") {
name
}
}

The server will send the following response:

{
"data": {
"film": {
"title": "A New Hope"
},
"person": null
},
"errors": [
{
"message": "No entry in local cache for https://swapi.dev/api/people/m�H/",
"locations": [
{
"line": 35,
"column": 3
}
],
"path": [
"person"
]
}
]
}

Note that while there are errors, the query successfully returned the title of the film: A New Hope. In general, any error while executing an operation bubbles up to the next nullable field. In this case data?.person is nil. In the worst case, GraphQLResult.data may be nil if everything else is non-nullable.

Apollo iOS gives you access to both the data and the errors in the GraphQLResult class:

apollo.fetch(query: HeroNameQuery()) { result in
switch result {
case .success(let response):
if let errors = response.errors {
// GraphQL errors
}
let film = response.data?.film // Exists
let person = response.data?.person // nil
case .failure(let error):
// Network error
print(error)
}
}

GraphQL errors are returned as type-safe GraphQLError values. These values are parsed from the response as described in the section on response format errors in the GraphQL specification.

Edit on GitHub
Previous
Operation Arguments
Next
Type Conditions