0
0
GraphQLquery~5 mins

Custom error extensions in GraphQL

Choose your learning style9 modes available
Introduction

Custom error extensions help you add extra details to errors in GraphQL. This makes it easier to understand and fix problems.

When you want to give users more information about why a request failed.
When you need to send error codes that your app can use to handle errors better.
When you want to include extra data like which field caused the error.
When debugging and you want to log detailed error info.
When building APIs that need clear error messages for clients.
Syntax
GraphQL
throw new GraphQLError('Error message', {
  extensions: {
    code: 'ERROR_CODE',
    detail: 'Extra info about the error'
  }
});
The extensions object can hold any extra info you want to send with the error.
The code field inside extensions is often used to identify error types.
Examples
This example sends a simple error with a code to identify the problem.
GraphQL
throw new GraphQLError('User not found', {
  extensions: { code: 'USER_NOT_FOUND' }
});
This example adds a list of invalid arguments to help the client fix the input.
GraphQL
throw new GraphQLError('Invalid input', {
  extensions: {
    code: 'BAD_USER_INPUT',
    invalidArgs: ['email']
  }
});
This example explains why the user is forbidden from accessing a resource.
GraphQL
throw new GraphQLError('Permission denied', {
  extensions: {
    code: 'FORBIDDEN',
    reason: 'User does not have admin rights'
  }
});
Sample Program

This code checks if a user exists. If not, it throws a GraphQL error with a custom code. The catch block prints the error extensions as JSON.

GraphQL
const { GraphQLError } = require('graphql');

function checkUser(user) {
  if (!user) {
    throw new GraphQLError('User not found', {
      extensions: { code: 'USER_NOT_FOUND' }
    });
  }
  return 'User exists';
}

try {
  console.log(checkUser(null));
} catch (error) {
  console.log(JSON.stringify(error.extensions));
}
OutputSuccess
Important Notes

Always use meaningful codes in extensions.code to help clients handle errors.

You can add any extra fields inside extensions to provide more context.

Custom error extensions improve API clarity and debugging.

Summary

Custom error extensions add extra info to GraphQL errors.

Use extensions to send codes and details.

This helps clients understand and handle errors better.