GraphQL Error Handling

GraphQL errors are different from traditional REST error handling because a response can contain both data and errors.

For example:

{
  "data": {
    "user": null
  },
  "errors": [
    {
      "message": "User not found"
    }
  ]
}

The exact result depends on the field's nullability and the execution failure.

GraphQL errors can originate from validation, parsing, variable coercion, resolver execution, authorization, or other layers.

Consider:

type Query {
  user(id: ID!): User
}

Because user is nullable, an execution failure can result in user: null alongside an error.

Now consider:

type Query {
  user(id: ID!): User!
}

The non-null contract changes error propagation. If the resolver cannot produce a valid non-null user, GraphQL can propagate null to a nullable parent field, potentially causing a larger portion of the response to become null.

Production APIs should also avoid leaking sensitive internal information through error messages. Database stack traces, credentials, internal hostnames, and implementation details should not become client-facing errors.

A consistent error classification strategy helps clients distinguish expected business failures from unexpected infrastructure failures.

Do not expose internal errors

GraphQL error messages are part of an API response. Avoid exposing stack traces, database credentials, internal hostnames, or sensitive implementation details to clients.

Key Takeaways
  • GraphQL responses can contain both data and errors.
  • Field nullability affects error propagation.
  • Validation and execution errors have different origins.
  • Production error responses should not leak sensitive implementation details.
Knowledge Check

What can a GraphQL response contain when a resolver encounters an execution error?