From 91e0b64e6f95d270bd386bec5c6c0ef395c4182c Mon Sep 17 00:00:00 2001 From: Konstantin Simeonov Date: Mon, 15 Jul 2024 19:29:22 +0300 Subject: [PATCH] improve(validation): add location to error messages --- src/validation/validate.ts | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/validation/validate.ts b/src/validation/validate.ts index 7259874240..e81a91d650 100644 --- a/src/validation/validate.ts +++ b/src/validation/validate.ts @@ -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): Error { + const errorMessageWithLocations = errors + .map((error) => { + if (!error.locations?.length) { + return error.message; + } + + const locations = + error.locations + .map(({ line, column }) => `${line}:${column}`) + .join(', ') ?? ''; + 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. @@ -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); } } @@ -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); } }