Errors and partial responses

Intermediate · 35 min

A response can carry data and errors together. See how a failing field nulls itself or its parent, what errors holds, and why 200 is not success.

Before thisResolversNon-null and listsDataLoader and batching

Apollo GraphQL · 35 min

Errors and partial responses

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Apollo GraphQLReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A response may contain both `data` and `errors`. When one field fails, GraphQL nulls that field and reports the error with a `path`, and the other fields still return.
  • A failing non-null field cannot be null, so the null moves up to the nearest nullable parent; if there is none, the whole `data` becomes null.
  • Each error has a `message`, `locations`, a `path` and optional `extensions`; put a stable machine-readable `code` in `extensions` and never parse messages.
  • Validation failures, such as an unknown field, return only `errors` with no `data`, and the HTTP status is 200 unless the client asks for `application/graphql-response+json`.
  • Treat HTTP 200 as 'the server ran GraphQL', not 'the operation succeeded'; clients must check `errors` on every response.

The problem: one response, many fields

A REST request usually succeeds or fails as a unit, and the status code says which. A GraphQL operation asks for many fields at once, possibly from different backends. If the recommendations service is down but the user profile loaded fine, throwing away the whole response would be the worst possible behaviour. The page could still show the profile.

So GraphQL’s response is built to hold both. It is a JSON object with up to two top-level keys: data for what worked, errors for what did not.

A nullable field fails alone

I ran these against Yoga 6.1.0 and graphql-js 17.1.0. The schema has ok: String! and flaky: String, and flaky throws a GraphQLError with a code:

flaky: () => {
  throw new GraphQLError('Upstream unavailable', {
    extensions: { code: 'UPSTREAM_DOWN' },
  });
},

The query { ok flaky } returned:

{
  "errors": [{
    "message": "Upstream unavailable",
    "locations": [{ "line": 1, "column": 6 }],
    "path": ["flaky"],
    "extensions": { "code": "UPSTREAM_DOWN" }
  }],
  "data": { "ok": "fine", "flaky": null }
}

flaky is null, ok is intact, and the error says where it came from. path is the route from the root to the failed field, with list indexes as numbers. locations points into the query text. Both help a client attach the error to the right place.

The same works inside lists. For { list { id secret } }, where Item.secret throws for item 2:

{ "errors": [{ "message": "not allowed", "path": ["list", 1, "secret"],
    "extensions": { "code": "FORBIDDEN" } }],
  "data": { "list": [{ "id": "1", "secret": "a" }, { "id": "2", "secret": null }] } }

One item lost one field; the other item and the list survived.

Non-null fields pass the failure upward

Non-null (!) is a promise that a field is never null, so when a resolver fails there is no value that keeps the promise. GraphQL moves the null to the parent. I checked three shapes:

Query.wrapper: Wrapper (nullable); Wrapper.inner: String!
{ ok wrapper { inner } }  ->  data: { ok: "fine", wrapper: null }

Item.score: Int!, Query.items: [Item!]!, score throws for item 2
{ items { id score } }    ->  data: null

Item.score: Int!, Query.items: [Item]!
{ items { id score } }    ->  data: { items: [ {…}, null, {…} ] }

Item.score: Int, Query.items: [Item!]!
{ items { id score } }    ->  data: { items: [ {score: 10}, {score: null}, {score: 10} ] }

Pay attention to the second one. One failing score deleted the whole response, because Int! made the item null, [Item!]! forbade null items, so the list was null, and the root items field was non-null too. A single slow dependency on one item blanked out everything. The more ! you add, the larger the blast radius. Nullability in practice takes this on in detail.

Errors that stop everything

Not all errors come from resolvers. If the document is invalid, nothing runs and there is no data at all:

{ "errors": [{ "message": "Cannot query field \"nope\" on type \"Query\".",
    "locations": [{ "line": 1, "column": 3 }],
    "extensions": { "code": "GRAPHQL_VALIDATION_FAILED" } }] }

A syntax error or missing required variable does the same. These are client bugs, caught before execution.

What does the HTTP status say?

On a plain application/json request, the invalid query above came back with HTTP 200. A request with Accept: application/graphql-response+json got 400. Partial failures such as flaky return 200 in both modes. The GraphQL over HTTP lesson explains the two content types.

This is the part that surprises REST developers. A monitoring tool that watches for 5xx sees nothing, because the error is in the body. So do two things: have clients check errors on every response, and have servers log errors and count them by extensions.code.

What the client sees from a real fault

A plain Error thrown in a resolver is not shown to the client. For throw new Error('connect ECONNREFUSED 10.0.0.5:5432'), Yoga returned:

{ "errors": [{ "message": "Unexpected error.", "path": ["throwsPlain"],
    "extensions": { "code": "INTERNAL_SERVER_ERROR" } }], "data": { "throwsPlain": null } }

That masking is deliberate: internals such as hostnames should not leak. It means a resolver that wants a message shown must throw a GraphQLError. The same masking hid a Cannot return null for non-nullable field violation; the real reason is in the server log, so read it when a client reports Unexpected error..

Choosing between errors and data

Two homes for failure, and they answer different questions:

  • errors: something unexpected or a violation of the contract: a timeout, a bug, an authorization failure, a bad document. Handled by generic code.
  • Data: an expected outcome the user will act on: invalid form input, “email already taken”. Modelled as userErrors on a mutation payload or as a union such as CreatePostResult = Post | ValidationFailure; see unions.

Give every error a stable extensions.code, and tell clients what the codes are. Clients should branch on code, never on message text. For how a REST-style API encodes the same ideas, compare structured error handling and RFC 7807.

What the video covers

The video is Sasha Solomon’s talk “200 OK! Error Handling in GraphQL,” published on Apollo GraphQL’s channel in 2020; the description introduces her as a Senior Software Engineer at Twitter talking about error handling in GraphQL. It runs 35 minutes. I could not read a transcript, so beyond the title and description I cannot say what it covers in detail. It is a conference talk rather than a tutorial, and its server examples may use Apollo Server rather than Yoga, so treat the code in this lesson as the reference. Warren Day’s error-handling chapter is a shorter, code-along alternative.

Where this fits

You have the full server loop: schema, resolvers, context, a database, batching and error behaviour. The next group steps back from implementation and asks what makes a schema good to live with. Next: schema design principles.

Check yourself

  1. 01A query selects `ok` and `flaky`, and `flaky` throws. What comes back?

    `data` with `ok` returned and `flaky` null, plus an `errors` entry whose `path` is `["flaky"]`. The working field is not lost.

  2. 02What changes if the failing field is declared `String!`?

    It cannot be null, so GraphQL nulls its parent instead, and keeps going up through non-null parents until it reaches a nullable one. With none, `data` itself is null.

  3. 03How should a client decide how to react to an error?

    By `extensions.code`, a stable identifier like `FORBIDDEN`, rather than by matching message text, which can change or be translated.

  4. 04Why might an HTTP 200 response still mean the operation failed?

    GraphQL reports field errors inside the body. Only a client that asks for `application/graphql-response+json` gets a 400 for an invalid operation.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark