0
0
GraphqlHow-ToBeginner · 3 min read

How to Format Error in Apollo Server: Simple Guide

In Apollo Server, you can format errors by using the formatError function in the server configuration. This function lets you customize the error message and other details before sending them to the client.
📐

Syntax

The formatError function receives an error object and returns a new error object with customized fields. It is set in the Apollo Server constructor options.

  • error: The original error object.
  • Return value: A new error object with formatted message or additional fields.
javascript
const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError: (error) => {
    // Customize error here
    return {
      message: error.message,
      code: error.extensions?.code || 'INTERNAL_SERVER_ERROR'
    };
  }
});
💻

Example

This example shows how to format errors to include a custom message and error code when a resolver throws an error.

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

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

const resolvers = {
  Query: {
    hello: (_, { name }) => {
      if (!name) {
        throw new Error('Name is required');
      }
      return `Hello, ${name}!`;
    }
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError: (error) => {
    return {
      message: error.message,
      code: error.extensions?.code || 'BAD_USER_INPUT'
    };
  }
});

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
Output
Server ready at http://localhost:4000/
⚠️

Common Pitfalls

One common mistake is to forget to check if error.extensions exists before accessing code, which can cause runtime errors. Another is to expose sensitive error details to clients unintentionally.

Always sanitize error messages and avoid leaking internal server details.

javascript
/* Wrong way: Accessing extensions.code without check */
formatError: (error) => {
  return {
    message: error.message,
    code: error.extensions.code // May cause error if extensions is undefined
  };
}

/* Right way: Safe access with fallback */
formatError: (error) => {
  return {
    message: error.message,
    code: error.extensions?.code || 'INTERNAL_SERVER_ERROR'
  };
}
📊

Quick Reference

Tips for formatting errors in Apollo Server:

  • Use formatError to customize error output.
  • Always check for error.extensions before accessing properties.
  • Sanitize messages to avoid leaking sensitive info.
  • Return consistent error codes for easier client handling.

Key Takeaways

Use the formatError function in Apollo Server to customize error messages sent to clients.
Always safely access error properties like extensions.code to avoid runtime errors.
Sanitize error messages to prevent exposing sensitive server details.
Return consistent error codes to help clients handle errors properly.