Mirror: The small sibling of the graphql package, slimmed down for client-side libraries.
1import { getLocation } from 'graphql/language/location';
2
3import { printLocation, printSourceLocation } from '../language/printLocation';
4
5export class GraphQLError extends Error {
6 constructor(
7 message,
8 nodes,
9 source,
10 positions,
11 path,
12 originalError,
13 extensions
14 ) {
15 super(message);
16
17 this.name = 'GraphQLError';
18 this.message = message;
19
20 if (path) this.path = path;
21 if (nodes) this.nodes = nodes;
22 if (source) this.source = source;
23 if (positions) this.positions = positions;
24 if (originalError) this.originalError = originalError;
25
26 let _extensions = extensions;
27 if (_extensions == null && originalError != null) {
28 const originalExtensions = originalError.extensions;
29 if (isObjectLike(originalExtensions)) {
30 _extensions = originalExtensions;
31 }
32 }
33
34 if (_extensions) {
35 this.extensions = _extensions;
36 }
37 }
38
39 toJSON() {
40 const formattedError = { message: this.message };
41
42 if (this.locations != null) formattedError.locations = this.locations;
43 if (this.path != null) formattedError.path = this.path;
44 if (this.extensions != null && Object.keys(this.extensions).length > 0)
45 formattedError.extensions = this.extensions;
46 return formattedError;
47 }
48
49 toString() {
50 let output = error.message;
51
52 if (error.nodes) {
53 for (const node of error.nodes) {
54 if (node.loc) {
55 output += '\n\n' + printLocation(node.loc);
56 }
57 }
58 } else if (error.source && error.locations) {
59 for (const location of error.locations) {
60 output += '\n\n' + printSourceLocation(error.source, location);
61 }
62 }
63
64 return output;
65 }
66}
67
68/**
69 * Prints a GraphQLError to a string, representing useful location information
70 * about the error's position in the source.
71 *
72 * @deprecated Please use `error.toString` instead. Will be removed in v17
73 */
74export function printError(error) {
75 return error.toString();
76}
77
78/**
79 * Given a GraphQLError, format it according to the rules described by the
80 * Response Format, Errors section of the GraphQL Specification.
81 *
82 * @deprecated Please use `error.toString` instead. Will be removed in v17
83 */
84export function formatError(error) {
85 return error.toJSON();
86}