graphql-js icon indicating copy to clipboard operation
graphql-js copied to clipboard

Add generic type parameter to GraphQLError for typed extensions

Open raymondwang opened this issue 3 months ago • 2 comments

Per the spec:

The "extensions" entry in an execution result or request error result, if set, must have a map as its value. This entry is reserved for implementers to extend the protocol however they see fit, and hence there are no additional restrictions on its contents.

However, the GraphQLError type currently does not expose an option to extend the extensions field in the type system. This makes interacting with error extensions tedious, as consumers must explicitly cast the extensions for each error manually.

Before

// No validation occurs on input extensions when creating an error:
const error = new GraphQLError('Something went wrong', {
  extensions: {
    code: 'VALIDATION_ERROR',
    details: { timestamp: Date.now() },
  },
});

// Consumers must cast to access extension properties with strong types:
const code = error.extensions.code as string;
const timestamp = (error.extensions.details as { timestamp: number } | undefined)?.timestamp;

After

// Extensions can be explicitly defined:
interface FormattedExtensions extends GraphQLErrorExtensions {
  code: string;
  details?: { timestamp: number; };
}

// Create strongly typed errors with type validation on input extensions:
const error = new GraphQLError<FormattedExtensions>('Something went wrong', {
  extensions: {
    code: 'VALIDATION_ERROR',
    details: { timestamp: Date.now() },
  },
});

// Access extension properties with full type safety:
const code = error.extensions.code; // string
const timestamp = error.extensions.details?.timestamp; // number | undefined

This could be added to a few other places — I've added it to ExecutionResult, for instance — but I wanted to get a pulse check on this approach first.

raymondwang avatar Aug 27 '25 16:08 raymondwang