Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 ยท Schema Design

Modeling Errors

Decide which failures belong in the top-level errors array and which belong in the schema, and model them with result unions, payload fields and codes.

In How Execution Works and How Errors Behave you saw the built-in error channel: the top-level errors array. It is perfect for things that went wrong, such as a crashed database or a forbidden field. It is awkward for things that are normal: a user typed an email that is already registered, a coupon expired, a booking slot was taken a second ago. These are expected outcomes of a working system, and clients must react to each of them. This lesson shows how to put them into the schema, where they are typed, documented and impossible to forget.

Reminder: nothing here runs against a real GraphQL server. Schema and query text is read-only, and the runnable examples are small stand-ins in plain JavaScript.

Two kinds of failure

Two kinds of failure

Unexpected Bugs, outages, timeouts. Nobody planned for them.
Expected Invalid input, name taken, not enough stock.

Unexpected goes to the errors array. Expected goes into the schema.

1 / 2

If every validation message goes into errors, your monitoring cannot tell a real incident from a user mistyping an email, and clients end up matching text in message to decide what to show. If errors are in the schema, a client knows by reading the types which outcomes exist.

Style 1: user errors in the payload

The simplest schema-level approach, shown briefly in Schema Design Best Practices: the payload has the result field and a list of errors.

GRAPHQL
type Mutation {
  createUser(input: CreateUserInput!): CreateUserPayload!
}

type CreateUserPayload {
  user: User
  userErrors: [UserError!]!
}

type UserError {
  field: [String!]
  code: UserErrorCode!
  message: String!
}

enum UserErrorCode {
  REQUIRED
  TOO_SHORT
  ALREADY_TAKEN
  INVALID_FORMAT
}

On success userErrors is empty and user is set. On failure user is null and userErrors explains why, possibly with several entries at once, which is the big advantage for forms: all the problems can be shown together. The weakness: nothing in the type system forces the client to check userErrors before using user, and user has to be nullable.

The next stand-in builds such a payload. The validator collects every problem instead of stopping at the first. Read how it returns userErrors for bad input and a user for good input.

JS A mutation returning user errors in the payload

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note the first attempt: two problems reported at once, each with a field path the UI can use to place the message next to the right input. Every response here has no top-level errors key, and the HTTP status would be 200: from the server's point of view nothing went wrong.

Style 2: result unions

A union makes each outcome its own type, and the mutation returns the union. The client must handle each case, and fields exist only where they make sense: a success has a user, an error has a message, and nothing is nullable just to represent the other case.

GRAPHQL
union CreateUserResult = CreateUserSuccess | EmailTaken | InvalidInput

type CreateUserSuccess {
  user: User!
}

type EmailTaken {
  message: String!
  suggestedEmail: String
}

type InvalidInput {
  message: String!
  problems: [FieldProblem!]!
}

type FieldProblem {
  field: String!
  message: String!
}

type Mutation {
  createUser(input: CreateUserInput!): CreateUserResult!
}

The client asks with inline fragments (see Enums, Interfaces and Unions) and __typename:

GRAPHQL
mutation Register($input: CreateUserInput!) {
  createUser(input: $input) {
    __typename
    ... on CreateUserSuccess { user { id email } }
    ... on EmailTaken { message suggestedEmail }
    ... on InvalidInput { message problems { field message } }
  }
}

Each failure type can carry data that only that failure has (suggestedEmail). With code generation, a TypeScript client gets a discriminated union and the compiler complains when a case is not handled. Adding a new error type later means adding a member to the union: clients that switch exhaustively learn about it at compile time, though old clients still need a default branch.

The stand-in below implements the union with a __typename on every result and a client function that handles each case.

JS A mutation returning a result union

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The default branch is not decoration. A server may add a new member to the union next month, and a client built before that must not crash on a __typename it has never seen.

Error codes in extensions

For failures that stay in the top-level errors array (not logged in, not allowed, rate limited, not found), give every entry a stable machine-readable code under extensions:

JSON
{
  "data": { "order": null },
  "errors": [
    {
      "message": "You must be signed in to view orders.",
      "path": ["order"],
      "extensions": { "code": "UNAUTHENTICATED" }
    }
  ]
}

Document the codes you use, keep the list short, and treat the codes as part of the API: clients branch on them, so renaming one is a breaking change. Messages, by contrast, are for humans and may be rewritten or translated. Never leak stack traces, SQL or file paths in a message; log the detail on the server and return something general.

Which style to choose?

Situation Good fit
Form validation with many field messages Payload userErrors, or a union with a problems list
A few distinct outcomes with different data Result union
Not logged in, forbidden, rate limited Top-level error with a code in extensions
Bug, outage, timeout Top-level error, generic message
"Not found" for a lookup query Often just null (nullable field)

Pick one style for expected errors and use it everywhere; mixing them mutation by mutation forces clients to learn several conventions. A common compromise is a union for mutations and plain nullable fields for lookups. Also remember that the schema is only a contract if the server keeps it: do not throw an exception for something your schema models as a result.

Ask this about any failure: "Should the user's next click depend on it?" If yes, it is part of the product and belongs in the schema.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which failure belongs in the top-level errors array rather than in the schema?

    An outage is unexpected and not something clients can plan around. The others are normal outcomes that the schema can describe.
  2. 2. What is a main advantage of a result union over a payload with a nullable result and an errors list?

    Each case has exactly the fields that make sense for it, and typed clients can check that every case is handled.
  3. 3. Why should clients branch on extensions.code instead of message?

    Codes are part of the contract. Messages are for humans and may be reworded.
  4. 4. A new member is added to a result union. What should an older client do with an unknown __typename?

    Schemas evolve by adding. A default branch keeps older clients working.

Summary

  • Expected failures (validation, conflicts, business rules) belong in the schema; unexpected ones go to the top-level errors.
  • Payload types with userErrors are simple and report many problems at once.
  • Result unions give each outcome its own type and make clients handle every case.
  • Put a stable code in extensions for errors in the top-level array and never leak internals.
  • Choose one style and use it consistently.

Next: Authentication and Authorization.