Skip to content

Commit 91e0b64

Browse files
improve(validation): add location to error messages
1 parent e1ceb8f commit 91e0b64

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

Diff for: src/validation/validate.ts

+24-2
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,28 @@ export function validateSDL(
107107
return errors;
108108
}
109109

110+
/**
111+
* Combine multiple errors into a single error, whose message
112+
* contains the error messages and their line:column on separate lines.
113+
*/
114+
function combineErrorsWithLocation(errors: ReadonlyArray<GraphQLError>): Error {
115+
const errorMessageWithLocations = errors
116+
.map((error) => {
117+
if (!error.locations?.length) {
118+
return error.message;
119+
}
120+
121+
const locations =
122+
error.locations
123+
.map(({ line, column }) => `${line}:${column}`)
124+
.join(', ') ?? '';
125+
return `${error.message} (${locations})`;
126+
})
127+
.join('\n\n');
128+
129+
return new Error(errorMessageWithLocations);
130+
}
131+
110132
/**
111133
* Utility function which asserts a SDL document is valid by throwing an error
112134
* if it is invalid.
@@ -116,7 +138,7 @@ export function validateSDL(
116138
export function assertValidSDL(documentAST: DocumentNode): void {
117139
const errors = validateSDL(documentAST);
118140
if (errors.length !== 0) {
119-
throw new Error(errors.map((error) => error.message).join('\n\n'));
141+
throw combineErrorsWithLocation(errors);
120142
}
121143
}
122144

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

0 commit comments

Comments
 (0)