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

Preserve non-error values thrown from resolvers #3384

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/error/__tests__/locatedError-test.ts
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
@@ -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
@@ -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;
}
}