0
0
GraphqlHow-ToBeginner · 4 min read

How to Use Extensions in Error in GraphQL

In GraphQL, you can add extra information to errors using the extensions field inside the error object. This field is a flexible place to include custom data like error codes or debugging info, which clients can use to handle errors better.
📐

Syntax

The extensions field is an optional object inside a GraphQL error. It can hold any key-value pairs you want to send along with the error message.

Typical structure:

{
  "errors": [
    {
      "message": "Error message",
      "extensions": {
        "code": "ERROR_CODE",
        "details": "Additional info"
      }
    }
  ]
}

Here, message is the error text, and extensions holds extra data like code or details.

json
{
  "errors": [
    {
      "message": "Error message",
      "extensions": {
        "code": "ERROR_CODE",
        "details": "Additional info"
      }
    }
  ]
}
💻

Example

This example shows how to throw a GraphQL error with an extensions field using Apollo Server in JavaScript. The extensions object includes a custom error code and a timestamp.

javascript
const { ApolloServer, gql, UserInputError } = require('apollo-server');

const typeDefs = gql`
  type Query {
    greet(name: String!): String
  }
`;

const resolvers = {
  Query: {
    greet: (_, { name }) => {
      if (name.length < 3) {
        throw new UserInputError('Name too short', {
          extensions: {
            code: 'NAME_TOO_SHORT',
            timestamp: new Date().toISOString()
          }
        });
      }
      return `Hello, ${name}!`;
    }
  }
};

const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
Output
{ "errors": [ { "message": "Name too short", "extensions": { "code": "NAME_TOO_SHORT", "timestamp": "2024-06-01T12:00:00.000Z" } } ] }
⚠️

Common Pitfalls

  • Not using extensions as an object: The extensions field must be an object, not a string or array.
  • Overloading extensions with sensitive data: Avoid putting private info in extensions as it is sent to clients.
  • Ignoring standard error codes: Use consistent error codes in extensions.code to help clients handle errors properly.
javascript
/* Wrong way: extensions as a string */
throw new Error('Failed');
throw Object.assign(new Error('Failed'), { extensions: 'Not an object' });

/* Right way: extensions as an object */
throw Object.assign(new Error('Failed'), { extensions: { code: 'FAILED' } });
📊

Quick Reference

FieldDescriptionExample
messageThe main error message shown to clients"Invalid input"
extensionsOptional object with extra error info{"code": "BAD_USER_INPUT"}
extensions.codeCustom error code string"UNAUTHENTICATED"
extensions.timestampOptional timestamp of error"2024-06-01T12:00:00Z"

Key Takeaways

Use the extensions field in GraphQL errors to send extra error details to clients.
The extensions field must be an object with key-value pairs, not a string or array.
Include consistent error codes in extensions.code to help clients handle errors.
Avoid putting sensitive information in extensions as it is exposed to clients.
Extensions enhance error communication without changing the main error message.