Introduction
Custom error extensions help you add extra details to errors in GraphQL. This makes it easier to understand and fix problems.
Custom error extensions help you add extra details to errors in GraphQL. This makes it easier to understand and fix problems.
throw new GraphQLError('Error message', { extensions: { code: 'ERROR_CODE', detail: 'Extra info about the error' } });
extensions object can hold any extra info you want to send with the error.code field inside extensions is often used to identify error types.throw new GraphQLError('User not found', { extensions: { code: 'USER_NOT_FOUND' } });
throw new GraphQLError('Invalid input', { extensions: { code: 'BAD_USER_INPUT', invalidArgs: ['email'] } });
throw new GraphQLError('Permission denied', { extensions: { code: 'FORBIDDEN', reason: 'User does not have admin rights' } });
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.
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)); }
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.
Custom error extensions add extra info to GraphQL errors.
Use extensions to send codes and details.
This helps clients understand and handle errors better.
extensions in GraphQL error responses?{"errors":[{"message":"Not found","extensions":{"code":"NOT_FOUND","timestamp":"2024-06-01T12:00:00Z"}}]}extensions field?{ message: 'Unauthorized', extensions: 'AUTH_ERROR' }Pass the test and this pattern moves unknown