Skip to content

Commit

Permalink
GraphQLError: keep extensions always present
Browse files Browse the repository at this point in the history
Backport #3313
  • Loading branch information
IvanGoncharov committed Oct 26, 2021
1 parent d8ca570 commit 482237a
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/error/GraphQLError.d.ts
Expand Up @@ -81,7 +81,7 @@ export class GraphQLError extends Error {
/**
* Extension fields to add to the formatted error.
*/
readonly extensions: { [key: string]: any } | undefined;
readonly extensions: { [key: string]: any };
}

/**
Expand Down
7 changes: 4 additions & 3 deletions src/error/GraphQLError.js
Expand Up @@ -61,7 +61,7 @@ export class GraphQLError extends Error {
/**
* Extension fields to add to the formatted error.
*/
+extensions: { [key: string]: mixed, ... } | void;
+extensions: { [key: string]: mixed, ... };

constructor(
message: string,
Expand Down Expand Up @@ -101,7 +101,7 @@ export class GraphQLError extends Error {
? positions.map((pos) => getLocation(source, pos))
: nodeLocations?.map((loc) => getLocation(loc.source, loc.start));

this.extensions = extensions ?? undefined;
this.extensions = extensions ?? {};

const originalExtensions = originalError?.extensions;
if (isObjectLike(originalExtensions)) {
Expand All @@ -119,7 +119,8 @@ export class GraphQLError extends Error {
enumerable: this.path != null,
},
extensions: {
enumerable: this.extensions != null,
enumerable:
this.extensions != null && Object.keys(this.extensions).length > 0,
},
name: { enumerable: false },
nodes: { enumerable: false },
Expand Down
8 changes: 6 additions & 2 deletions src/error/__tests__/GraphQLError-test.js
Expand Up @@ -28,10 +28,14 @@ describe('GraphQLError', () => {
expect(new GraphQLError('str')).to.be.instanceof(GraphQLError);
});

it('has a name, message, and stack trace', () => {
it('has a name, message, extensions, and stack trace', () => {
const e = new GraphQLError('msg');

expect(e).to.include({ name: 'GraphQLError', message: 'msg' });
expect(e).to.deep.include({
name: 'GraphQLError',
message: 'msg',
extensions: {},
});
expect(e.stack).to.be.a('string');
});

Expand Down
2 changes: 1 addition & 1 deletion src/error/formatError.js
Expand Up @@ -15,7 +15,7 @@ export function formatError(error: GraphQLError): GraphQLFormattedError {
const path = error.path;
const extensions = error.extensions;

return extensions
return extensions && Object.keys(extensions).length > 0
? { message, locations, path, extensions }
: { message, locations, path };
}
Expand Down

0 comments on commit 482237a

Please sign in to comment.