Skip to content

Error Handling in GraphQL

Error handling in GraphQL is essential for building robust, user-friendly APIs. Unlike REST, where HTTP status codes often signal success or failure, GraphQL typically uses a 200 OK response — even when errors occur. This makes understanding and managing GraphQL errors especially important.


Structure of a GraphQL Error Response

A standard GraphQL error response includes two top-level fields:

  • data: Partial or null response data
  • errors: An array of error objects

Example

{
  "data": {
    "user": null
  },
  "errors": [
    {
      "message": "User not found",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["user"]
    }
  ]
}

Common Error Types

1. Validation Errors

Occurs when a query is malformed or references non-existent fields.

{
  "errors": [
    {
      "message": "Cannot query field 'emial' on type 'User'. Did you mean 'email'?",
      "locations": [{ "line": 3, "column": 5 }]
    }
  ]
}

2. Execution Errors

Thrown during resolver execution — e.g., database errors, missing data, permission issues.

{
  "errors": [
    {
      "message": "User not authorized to access this resource",
      "path": ["user", "email"]
    }
  ]
}

3. Partial Failures

GraphQL allows returning partial success — some fields succeed, others fail.

{
  "data": {
    "user": {
      "id": "1",
      "email": null
    }
  },
  "errors": [
    {
      "message": "Email is private",
      "path": ["user", "email"]
    }
  ]
}

Custom Error Handling

You can throw custom errors from your resolvers and enrich them with additional metadata.

Example in Apollo Server (Node.js)
const { AuthenticationError } = require("apollo-server");

const resolvers = {
  Query: {
    me: (parent, args, context) => {
      if (!context.user) {
        throw new AuthenticationError("You must be logged in");
      }
      return context.user;
    },
  },
};

Best Practices

  • Always return useful error messages – but avoid leaking sensitive info.
  • Use HTTP status codes when applicable (for non-query errors, like auth failures).
  • Log errors on the server side for debugging and audits.
  • Structure errors with extensions for machine-readable codes and actions.

Adding Metadata with extensions

You can include structured metadata using the extensions field.

{
  "errors": [
    {
      "message": "Permission denied",
      "extensions": {
        "code": "FORBIDDEN",
        "timestamp": "2025-08-05T12:34:56Z"
      }
    }
  ]
}

Tools & Libraries


Summary

Error Type Cause Recoverable?
Validation Error Query syntax or schema mismatch
Execution Error Resolver failure, DB errors, etc.
Partial Failure Some fields fail, others succeed