Error Handling in GraphQL

GraphQL errors sit in the errors array, together with data that may be partial. A request error (can't be read, fails validation, wrong variables) stops…

In REST, a book that doesn't exist gets a 404, and that's it. One GraphQL request can ask for many things at once, so one part failing doesn't have to fail everything. Errors arrive inside the response body, in the errors array, and often together with data that's partly filled in.

It's like ordering two books by courier. One is there, the other turns out not to be in the warehouse. The courier still delivers the book that's there, plus a note: "the second book wasn't found, here's why". The parcel is data, the note is errors.

Two kinds of error

The GraphQL specification tells two kinds apart:

What one error holds

This query asks for two books, and book 99 isn't in the shop:

{
  rainbow: book(id: 1) {
    title
  }
  missing: book(id: 99) {
    title
  }
}

The Bookshop response:

{
  "errors": [
    {
      "message": "Book not found",
      "locations": [{ "line": 5, "column": 3 }],
      "path": ["missing"],
      "extensions": { "code": "NOT_FOUND" }
    }
  ],
  "data": {
    "rainbow": { "title": "The Rainbow Troops" },
    "missing": null
  }
}

The Rainbow Troops still arrives, missing is null, and errors says why.

Key What it holds
message an explanation for the developer. Always present.
locations the line and column in the query text where the problem is, counting from 1
path the position in the response that became null: its key (here the alias missing), and an index inside a list, as in ["books", 2, "author"]
extensions a free map for the server's extra information, such as code

path is what tells a null caused by an error from a null that's the real value. The specification also asks servers not to add keys beside these four: extra information goes in extensions.

extensions.code: a code for programs

message is written for people and may change. Programs should read a code in extensions. The GraphQL specification doesn't say what goes there. The names used most come from Apollo Server:

Code When Apollo Server uses it
GRAPHQL_PARSE_FAILED the query can't be read
GRAPHQL_VALIDATION_FAILED the query doesn't fit the schema
BAD_USER_INPUT the variables or an argument aren't valid
OPERATION_RESOLUTION_FAILURE it can't tell which operation to run
INTERNAL_SERVER_ERROR a resolver error with no code of its own

Other codes you choose yourself, like NOT_FOUND, or UNAUTHENTICATED and FORBIDDEN, which Apollo's documentation uses for auth. In a resolver:

import { GraphQLError } from "graphql";

const book = books.find((b) => String(b.id) === args.id);
if (!book) {
  throw new GraphQLError("Book not found", { extensions: { code: "NOT_FOUND" } });
}

On the client, branch on the code, not on the message's text: if (error.extensions?.code === "NOT_FOUND") showNotFoundPage().

Hiding internal errors in production

When the authors' database is down, the Book.author resolver throws the database driver's error, and its message leaks as it is:

{ "message": "connect ECONNREFUSED 10.0.0.5:5432", "path": ["book", "author"] }

That's an internal server's address, and users can do nothing with it. In production, replace the message of an unexpected error and keep the original in the server's log. In Apollo Server that's formatError:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError: (formattedError, error) => {
    if (formattedError.extensions?.code === "INTERNAL_SERVER_ERROR") {
      console.error(error); // the original still goes in the server's log
      return { ...formattedError, message: "Internal server error" };
    }
    return formattedError;
  },
});

Errors meant for the client, like NOT_FOUND and BAD_USER_INPUT, are left alone. GraphQL Yoga masks errors like this by default. One more thing: as long as NODE_ENV is not production, Apollo Server adds extensions.stacktrace, with file paths on the server, to every error. Set NODE_ENV=production on the real server, or write includeStacktraceInErrorResponses: false.

Errors as data: the UpdateStockResult union

A negative stock isn't the server breaking. It's an ordinary mistake from a form that has to be shown to the user. The errors as data pattern puts it in the schema. For this lesson, the Bookshop's updateStock returns a union:

type Mutation {
  updateStock(id: ID!, stock: Int!): UpdateStockResult
}

union UpdateStockResult = Book | StockError

type StockError {
  message: String!
}
mutation {
  updateStock(id: 2, stock: -1) {
    __typename
    ... on Book {
      title
      stock
    }
    ... on StockError {
      message
    }
  }
}
{ "data": { "updateStock": { "__typename": "StockError", "message": "Stock cannot be negative" } } }

No errors at all. The resolver only needs if (stock < 0) return { message: "Stock cannot be negative" };, and __resolveType picks Book or StockError. Compare the version that throws: updateStock becomes null, and the message sits in errors.

The userErrors pattern from the "Mutations" lesson is another way to the same idea.

HTTP status: two media types

The GraphQL over HTTP draft specification uses the media type application/graphql-response+json. With it, the client knows the body is surely a GraphQL response, so the server may use the right 4xx status. With the older application/json, many servers, Apollo Server included, answer 200 once the operation runs.

Case Draft, application/graphql-response+json Apollo Server, application/json
Success, no errors 200 200
Partial data plus errors 294 200
Can't be read 400 400
Fails validation 422 400
Variables don't fit 422 400

The code 294 (Partial Success) isn't officially registered yet, so a client that doesn't know it treats it like 200. Whatever the media type, the client must still read errors in the body.

⚠️ Errors that slip through, leak, or carry the wrong code

TL;DR: GraphQL errors sit in the errors array, together with data that may be partial. A request error (can't be read, fails validation, wrong variables) stops everything with no data; an execution error makes one field null and the rest is still sent. Each error has a message, locations, a path and extensions, a free map for metadata such as a code. Codes like BAD_USER_INPUT and INTERNAL_SERVER_ERROR are Apollo Server's convention, not part of the specification. In production, mask internal error messages and keep the originals in the log. Expected mistakes can become data through a union like UpdateStockResult = Book | StockError. HTTP status: the GraphQL over HTTP draft with application/graphql-response+json uses 294, 400 and 422; with application/json, many servers answer 200. Always read the body.

⚡ One part fails, the rest still arrives

Write:

{
  rainbow: book(id: 1) {
    title
  }
  missing: book(id: 99) {
    title
  }
}
Guess first: book 99 isn't in the shop. Does The Rainbow Troops fail too?

No. The Rainbow Troops still arrives in data, missing becomes null, and errors says why, with "path": ["missing"].

Meaning: An error while running makes only one field null. A request error (can't be read, fails validation) is different: it stops everything, with no data.

⚡ extensions.code is for programs

Write:

throw new GraphQLError("Book not found", { extensions: { code: "NOT_FOUND" } });

Meaning: extensions is a free map for your own error metadata, such as a code. message is written for people and may change, so programs branch on extensions.code.

⚡ Expected mistakes become data

Meaning: A negative stock is an ordinary form mistake, not the server breaking. With union UpdateStockResult = Book | StockError, the mutation answers a StockError in data, with no errors. Internal errors like a database being down are still thrown, and their messages are masked in production.

What you will learn