Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for @experimental_disableErrorPropagation #4348

Merged
merged 7 commits into from
Feb 24, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions src/execution/__tests__/onerror-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { describe, it } from 'mocha';

import { expectJSON } from '../../__testUtils__/expectJSON.js';

import type { PromiseOrValue } from '../../jsutils/PromiseOrValue.js';

import { parse } from '../../language/parser.js';

import { buildSchema } from '../../utilities/buildASTSchema.js';

import { execute } from '../execute.js';
import type { ExecutionResult } from '../types.js';

const syncError = new Error('bar');

const throwingData = {
foo() {
throw syncError;
},
};

const schema = buildSchema(`
type Query {
foo : Int!
}

enum _ErrorAction { PROPAGATE, NULL }
directive @onError(action: _ErrorAction) on QUERY | MUTATION | SUBSCRIPTION
`);

function executeQuery(
query: string,
rootValue: unknown,
): PromiseOrValue<ExecutionResult> {
return execute({ schema, document: parse(query), rootValue });
}

describe('Execute: handles errors', () => {
it('with `@onError(action: NULL) returns null', async () => {
const query = `
query getFoo @onError(action: NULL) {
foo
}
`;
const result = await executeQuery(query, throwingData);
expectJSON(result).toDeepEqual({
data: { foo: null },
errors: [
{
message: 'bar',
path: ['foo'],
locations: [{ line: 3, column: 9 }],
},
],
});
});
it('with `@onError(action: PROPAGATE) propagates the error', async () => {
const query = `
query getFoo @onError(action: PROPAGATE) {
foo
}
`;
const result = await executeQuery(query, throwingData);
expectJSON(result).toDeepEqual({
data: null,
errors: [
{
message: 'bar',
path: ['foo'],
locations: [{ line: 3, column: 9 }],
},
],
});
});
it('by default propagates the error', async () => {
const query = `
query getFoo {
foo
}
`;
const result = await executeQuery(query, throwingData);
expectJSON(result).toDeepEqual({
data: null,
errors: [
{
message: 'bar',
path: ['foo'],
locations: [{ line: 3, column: 9 }],
},
],
});
});
});
16 changes: 14 additions & 2 deletions src/execution/execute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ import {
isNonNullType,
isObjectType,
} from '../type/definition.js';
import { GraphQLStreamDirective } from '../type/directives.js';
import {
ErrorAction,
GraphQLOnErrorDirective,
GraphQLStreamDirective,
} from '../type/directives.js';
import type { GraphQLSchema } from '../type/schema.js';
import { assertValidSchema } from '../type/validate.js';

Expand Down Expand Up @@ -170,6 +174,7 @@ export interface ExecutionContext {
abortSignalListener: AbortSignalListener | undefined;
completed: boolean;
cancellableStreams: Set<CancellableStreamRecord> | undefined;
propagateErrors: boolean;
}

interface IncrementalContext {
Expand Down Expand Up @@ -314,6 +319,12 @@ export function executeQueryOrMutationOrSubscriptionEvent(
return ensureSinglePayload(result);
}

function propagateErrors(operation: OperationDefinitionNode): boolean {
const value = getDirectiveValues(GraphQLOnErrorDirective, operation);

return value?.action !== ErrorAction.NULL;
}

export function experimentalExecuteQueryOrMutationOrSubscriptionEvent(
validatedExecutionArgs: ValidatedExecutionArgs,
): PromiseOrValue<ExecutionResult | ExperimentalIncrementalExecutionResults> {
Expand All @@ -326,6 +337,7 @@ export function experimentalExecuteQueryOrMutationOrSubscriptionEvent(
: undefined,
completed: false,
cancellableStreams: undefined,
propagateErrors: propagateErrors(validatedExecutionArgs.operation),
};
try {
const {
Expand Down Expand Up @@ -976,7 +988,7 @@ function handleFieldError(

// If the field type is non-nullable, then it is resolved without any
// protection from errors, however it still properly locates the error.
if (isNonNullType(returnType)) {
if (exeContext.propagateErrors && isNonNullType(returnType)) {
throw error;
}

Expand Down
55 changes: 54 additions & 1 deletion src/type/directives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,19 @@ import { toObjMapWithSymbols } from '../jsutils/toObjMap.js';

import type { DirectiveDefinitionNode } from '../language/ast.js';
import { DirectiveLocation } from '../language/directiveLocation.js';
import { Kind } from '../language/kinds.js';

import { assertName } from './assertName.js';
import type {
GraphQLArgumentConfig,
GraphQLFieldNormalizedConfigArgumentMap,
GraphQLSchemaElement,
} from './definition.js';
import { GraphQLArgument, GraphQLNonNull } from './definition.js';
import {
GraphQLArgument,
GraphQLEnumType,
GraphQLNonNull,
} from './definition.js';
import { GraphQLBoolean, GraphQLInt, GraphQLString } from './scalars.js';

/**
Expand Down Expand Up @@ -276,6 +281,54 @@ export const GraphQLOneOfDirective: GraphQLDirective = new GraphQLDirective({
args: {},
});

/**
* Possible error handling actions.
*/
export const ErrorAction = {
PROPAGATE: 'PROPAGATE' as const,
NULL: 'NULL' as const,
} as const;

// eslint-disable-next-line @typescript-eslint/no-redeclare
export type ErrorAction = (typeof ErrorAction)[keyof typeof ErrorAction];

export const _ErrorAction = new GraphQLEnumType({
name: '_ErrorAction',
description: 'Possible error handling actions.',
values: {
PROPAGATE: {
value: ErrorAction.PROPAGATE,
description:
'Non-nullable positions that error cause the error to propagate to the nearest nullable ancestor position. The error is added to the "errors" list.',
},
NULL: {
value: ErrorAction.NULL,
description:
'Positions that error are replaced with a `null` and an error is added to the "errors" list.',
},
},
});

/**
* Controls how the executor handles errors.
*/
export const GraphQLOnErrorDirective = new GraphQLDirective({
name: 'onError',
description: 'Controls how the executor handles errors.',
locations: [
DirectiveLocation.QUERY,
DirectiveLocation.MUTATION,
DirectiveLocation.SUBSCRIPTION,
],
args: {
action: {
type: new GraphQLNonNull(_ErrorAction),
description: 'The action to execute when a field error is encountered.',
default: { literal: { kind: Kind.ENUM, value: 'PROPAGATE' } },
},
},
});

/**
* The full list of specified directives.
*/
Expand Down
Loading