Skip to content

Commit

Permalink
improve(validation): add location to error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
KonstantinSimeonov committed Jul 15, 2024
1 parent e1ceb8f commit 91e0b64
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/validation/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,28 @@ export function validateSDL(
return errors;
}

/**
* Combine multiple errors into a single error, whose message
* contains the error messages and their line:column on separate lines.
*/
function combineErrorsWithLocation(errors: ReadonlyArray<GraphQLError>): Error {
const errorMessageWithLocations = errors
.map((error) => {
if (!error.locations?.length) {
return error.message;
}

Check warning on line 119 in src/validation/validate.ts

View check run for this annotation

Codecov / codecov/patch

src/validation/validate.ts#L118-L119

Added lines #L118 - L119 were not covered by tests

const locations =
error.locations
.map(({ line, column }) => `${line}:${column}`)
.join(', ') ?? '';

Check warning on line 124 in src/validation/validate.ts

View check run for this annotation

Codecov / codecov/patch

src/validation/validate.ts#L124

Added line #L124 was not covered by tests
return `${error.message} (${locations})`;
})
.join('\n\n');

return new Error(errorMessageWithLocations);
}

/**
* Utility function which asserts a SDL document is valid by throwing an error
* if it is invalid.
Expand All @@ -116,7 +138,7 @@ export function validateSDL(
export function assertValidSDL(documentAST: DocumentNode): void {
const errors = validateSDL(documentAST);
if (errors.length !== 0) {
throw new Error(errors.map((error) => error.message).join('\n\n'));
throw combineErrorsWithLocation(errors);
}
}

Expand All @@ -132,6 +154,6 @@ export function assertValidSDLExtension(
): void {
const errors = validateSDL(documentAST, schema);
if (errors.length !== 0) {
throw new Error(errors.map((error) => error.message).join('\n\n'));
throw combineErrorsWithLocation(errors);
}
}

0 comments on commit 91e0b64

Please sign in to comment.