Skip to content

Commit

Permalink
fix(utils/createGraphQLError): Convert GraphQLError like originalErro…
Browse files Browse the repository at this point in the history
…r property to a GraphQLError
  • Loading branch information
ardatan committed Oct 10, 2023
1 parent 0e87254 commit b4c1759
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilly-scissors-wave.md
@@ -0,0 +1,5 @@
---
'@graphql-tools/utils': patch
---

Convert GraphQLError like originalError property to a GraphQLError
31 changes: 31 additions & 0 deletions packages/utils/src/errors.ts
Expand Up @@ -14,7 +14,38 @@ interface GraphQLErrorOptions {
extensions?: any;
}

const possibleGraphQLErrorProperties = [
'message',
'locations',
'path',
'nodes',
'source',
'positions',
'originalError',
'name',
'stack',
'extensions',
];

function isGraphQLErrorLike(error: any) {
return (
error != null &&
typeof error === 'object' &&
Object.keys(error).every(key => possibleGraphQLErrorProperties.includes(key))
);
}

export function createGraphQLError(message: string, options?: GraphQLErrorOptions): GraphQLError {
if (
options?.originalError &&
!(options.originalError instanceof Error) &&
isGraphQLErrorLike(options.originalError)
) {
options.originalError = createGraphQLError(
(options.originalError as any).message,
options.originalError,
);
}
if (versionInfo.major >= 17) {
return new (GraphQLError as any)(message, options);
}
Expand Down
19 changes: 19 additions & 0 deletions packages/utils/tests/createGraphQLError.test.ts
@@ -0,0 +1,19 @@
import { GraphQLError } from 'graphql';
import { createGraphQLError } from '../src/errors';

it('should handle non Error originalError', () => {
const error = createGraphQLError('message', {
originalError: {
message: 'originalError',
extensions: { code: 'ORIGINAL_ERROR' },
} as any,
});
expect(error.originalError).toBeInstanceOf(GraphQLError);
expect(error).toMatchObject({
message: 'message',
originalError: {
message: 'originalError',
extensions: { code: 'ORIGINAL_ERROR' },
},
});
});

0 comments on commit b4c1759

Please sign in to comment.