Skip to content

Commit

Permalink
Preserve non-error values thrown from resolvers
Browse files Browse the repository at this point in the history
Fixes #3379
  • Loading branch information
IvanGoncharov committed Nov 26, 2021
1 parent cce8a85 commit bce5fbc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
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;
}
}

0 comments on commit bce5fbc

Please sign in to comment.