diff --git a/src/error/GraphQLError.ts b/src/error/GraphQLError.ts index 77a5e78779..baeee9fde0 100644 --- a/src/error/GraphQLError.ts +++ b/src/error/GraphQLError.ts @@ -38,20 +38,22 @@ export interface GraphQLErrorOptions { source?: Maybe; positions?: Maybe>; path?: Maybe>; + /** @deprecated Prefer `cause` instead */ originalError?: Maybe; + cause?: unknown; extensions?: Maybe; } type BackwardsCompatibleArgs = | [options?: GraphQLErrorOptions] | [ - nodes?: GraphQLErrorOptions['nodes'], - source?: GraphQLErrorOptions['source'], - positions?: GraphQLErrorOptions['positions'], - path?: GraphQLErrorOptions['path'], - originalError?: GraphQLErrorOptions['originalError'], - extensions?: GraphQLErrorOptions['extensions'], - ]; + nodes?: GraphQLErrorOptions['nodes'], + source?: GraphQLErrorOptions['source'], + positions?: GraphQLErrorOptions['positions'], + path?: GraphQLErrorOptions['path'], + originalError?: GraphQLErrorOptions['originalError'], + extensions?: GraphQLErrorOptions['extensions'], + ]; function toNormalizedOptions( args: BackwardsCompatibleArgs, @@ -118,6 +120,7 @@ export class GraphQLError extends Error { /** * The original error thrown from a field resolver during execution. + * @deprecated Prefer using {@link Error.cause} instead */ readonly originalError: Error | undefined; @@ -140,13 +143,21 @@ export class GraphQLError extends Error { extensions?: Maybe, ); constructor(message: string, ...rawArgs: BackwardsCompatibleArgs) { - const { nodes, source, positions, path, originalError, extensions } = + const { nodes, source, positions, path, originalError, extensions, cause } = toNormalizedOptions(rawArgs); - super(message); + super(message, { cause: cause ?? originalError }); this.name = 'GraphQLError'; this.path = path ?? undefined; - this.originalError = originalError ?? undefined; + if (originalError) { + this.originalError = originalError; + } else if (cause instanceof Error) { + // If we guide users to migrate to `cause` instead of `originalError`, + // better not to break any downstream usages that still rely on `originalError` + this.originalError = cause; + } else { + this.originalError = undefined; + } // Compute list of blame nodes. this.nodes = undefinedIfEmpty(