0
0
GraphqlHow-ToBeginner · 4 min read

How to Return Custom Error in GraphQL: Simple Guide

In GraphQL, you return a custom error by throwing an Error object inside your resolver with a custom message or properties. You can also extend the error with additional fields like code to provide more details to the client.
📐

Syntax

To return a custom error in GraphQL, you throw an Error inside a resolver function. You can create a new Error with a message and add custom properties to it.

Example parts:

  • throw new Error('message'): Throws a basic error with a message.
  • Adding properties like error.extensions.code = 'BAD_USER_INPUT' to customize the error.
  • The GraphQL server sends this error back in the errors field of the response.
javascript
throw new Error('Custom error message');

// Or with custom properties
const error = new Error('Invalid input');
error.extensions = { code: 'BAD_USER_INPUT' };
throw error;
💻

Example

This example shows a simple GraphQL resolver that throws a custom error with a message and a code property when an invalid argument is passed.

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

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

const resolvers = {
  Query: {
    greet: (_, { name }) => {
      if (name.length < 3) {
        const error = new Error('Name must be at least 3 characters long');
        error.extensions = { code: 'BAD_USER_INPUT' };
        throw error;
      }
      return `Hello, ${name}!`;
    }
  }
};

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

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
Output
{ "errors": [ { "message": "Name must be at least 3 characters long", "extensions": { "code": "BAD_USER_INPUT" }, "locations": [{"line": 2, "column": 3}], "path": ["greet"] } ], "data": null }
⚠️

Common Pitfalls

Common mistakes when returning custom errors in GraphQL include:

  • Not throwing an error but returning an error message as data, which breaks GraphQL error handling.
  • Throwing generic errors without custom codes or messages, making it hard for clients to handle errors properly.
  • Not using extensions or custom properties to provide structured error info.

Always throw errors inside resolvers to trigger GraphQL's error response.

javascript
/* Wrong way: returning error message as data */
const resolversWrong = {
  Query: {
    greet: (_, { name }) => {
      if (name.length < 3) {
        return 'Error: Name too short'; // This is treated as valid data
      }
      return `Hello, ${name}!`;
    }
  }
};

/* Right way: throwing error */
const resolversRight = {
  Query: {
    greet: (_, { name }) => {
      if (name.length < 3) {
        const error = new Error('Name too short');
        error.extensions = { code: 'BAD_USER_INPUT' };
        throw error;
      }
      return `Hello, ${name}!`;
    }
  }
};
📊

Quick Reference

ConceptDescriptionExample
Throw ErrorUse throw new Error(message) inside resolverthrow new Error('Invalid input')
Custom PropertiesAdd fields like extensions.code for error typeconst e = new Error('Msg'); e.extensions = { code: 'BAD_USER_INPUT' }; throw e;
GraphQL ResponseErrors appear in errors field in response{"errors": [{"message": "Msg"}]}
Avoid Returning Errors as DataDo not return error messages as normal dataThrow errors instead of returning strings

Key Takeaways

Throw an Error inside your resolver to return a custom GraphQL error.
Add custom properties like code to the Error object for better client handling.
Never return error messages as normal data; always throw errors.
GraphQL sends thrown errors in the errors field of the response.
Use error extensions to provide structured error information.