0
0
GraphqlHow-ToBeginner · 3 min read

How to Log Errors in GraphQL: Simple Guide

To log errors in GraphQL, catch errors inside your resolver functions or use middleware like Apollo Server's formatError function to log them centrally. This lets you record error details while still returning useful error messages to clients.
📐

Syntax

In GraphQL, errors are usually logged inside resolver functions or through server-level error formatting. The key parts are:

  • try-catch blocks inside resolvers to catch and log errors.
  • formatError function in Apollo Server to customize and log errors globally.
javascript
const resolvers = {
  Query: {
    example: async () => {
      try {
        // Your logic here
      } catch (error) {
        console.error('Error in resolver:', error);
        throw error; // rethrow to send error to client
      }
    }
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError: (err) => {
    console.error('GraphQL Error:', err);
    return err;
  }
});
💻

Example

This example shows how to log errors inside a resolver and globally using Apollo Server's formatError. When an error occurs, it is logged to the console and sent back to the client.

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

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

const resolvers = {
  Query: {
    hello: (_, { name }) => {
      try {
        if (!name) {
          throw new Error('Name argument is required');
        }
        return `Hello, ${name}!`;
      } catch (error) {
        console.error('Resolver error:', error.message);
        throw error;
      }
    }
  }
};

const server = new ApolloServer({
  typeDefs,
  resolvers,
  formatError: (err) => {
    console.error('Formatted error:', err.message);
    return err;
  }
});

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
Output
Server ready at http://localhost:4000/ Resolver error: Name argument is required Formatted error: Name argument is required
⚠️

Common Pitfalls

Common mistakes when logging errors in GraphQL include:

  • Not rethrowing errors after logging, which prevents the client from receiving error details.
  • Logging sensitive information that should not be exposed.
  • Logging errors only in resolvers but missing global error formatting, leading to inconsistent logs.

Always log errors carefully and consider what information is safe to expose.

javascript
const resolversWrong = {
  Query: {
    example: () => {
      try {
        throw new Error('Oops');
      } catch (error) {
        console.error('Logged but not rethrown');
        // Missing throw here means client gets no error
      }
    }
  }
};

// Correct way:
const resolversRight = {
  Query: {
    example: () => {
      try {
        throw new Error('Oops');
      } catch (error) {
        console.error('Logged and rethrown');
        throw error;
      }
    }
  }
};
📊

Quick Reference

Tips for logging errors in GraphQL:

  • Use try-catch in resolvers to catch and log errors.
  • Use Apollo Server's formatError to log errors globally.
  • Always rethrow errors after logging to inform clients.
  • Be careful not to expose sensitive data in error messages.
  • Consider integrating with external logging services for production.

Key Takeaways

Log errors inside resolvers using try-catch and rethrow them to notify clients.
Use Apollo Server's formatError function to log errors globally in one place.
Avoid exposing sensitive information in error messages.
Consistent error logging helps with debugging and monitoring your GraphQL API.