Skip to content

Preserve non-error values thrown from resolvers #3384

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

Merged
merged 1 commit into from
Nov 28, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
11 changes: 11 additions & 0 deletions src/error/__tests__/locatedError-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ describe('locatedError', () => {
expect(locatedError(e, [], [])).to.deep.equal(e);
});

it('wraps non-errors', () => {
const testObject = Object.freeze({});
const error = locatedError(testObject, [], []);

expect(error).to.be.instanceOf(GraphQLError);
expect(error.originalError).to.include({
name: 'NonErrorThrown',
thrownValue: testObject,
});
});

it('passes GraphQLError-ish through', () => {
const e = new Error();
// @ts-expect-error
Expand Down
8 changes: 2 additions & 6 deletions src/error/locatedError.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { inspect } from '../jsutils/inspect';
import type { Maybe } from '../jsutils/Maybe';
import { toError } from '../jsutils/toError';

import type { ASTNode } from '../language/ast';

Expand All @@ -15,11 +15,7 @@ export function locatedError(
nodes: ASTNode | ReadonlyArray<ASTNode> | undefined | null,
path?: Maybe<ReadonlyArray<string | number>>,
): GraphQLError {
// Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface.
const originalError: Error | GraphQLError =
rawOriginalError instanceof Error
? rawOriginalError
: new Error('Unexpected error value: ' + inspect(rawOriginalError));
const originalError = toError(rawOriginalError);

// Note: this uses a brand-check to support GraphQL errors originating from other contexts.
if (isLocatedGraphQLError(originalError)) {
Expand Down
20 changes: 20 additions & 0 deletions src/jsutils/toError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { inspect } from './inspect';

/**
* Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface.
*/
export function toError(thrownValue: unknown): Error {
return thrownValue instanceof Error
? thrownValue
: new NonErrorThrown(thrownValue);
}

class NonErrorThrown extends Error {
thrownValue: unknown;

constructor(thrownValue: unknown) {
super('Unexpected error value: ' + inspect(thrownValue));
this.name = 'NonErrorThrown';
this.thrownValue = thrownValue;
}
}