Debian Codegraph @

src/graphql/error/graphql_error.py

raw
1 from sys import exc_info
2 from typing import Any, Collection, Dict, List, Optional, Union, TYPE_CHECKING
3
4 try:
5 from typing import TypedDict
6 except ImportError: # Python < 3.8
7 from typing_extensions import TypedDict
8
9 if TYPE_CHECKING:
10 from ..language.ast import Node # noqa: F401
11 from ..language.location import (
12 SourceLocation,
13 FormattedSourceLocation,
14 ) # noqa: F401
15 from ..language.source import Source # noqa: F401
16
17 __all__ = [
18 "GraphQLError",
19 "GraphQLErrorExtensions",
20 "GraphQLFormattedError",
21 "GraphQLFormattedErrorExtensions",
22 ]
23
24
25 # Custom extensions
26 GraphQLErrorExtensions = Dict[str, Any]
27 # Use a unique identifier name for your extension, for example the name of
28 # your library or project. Do not use a shortened identifier as this increases
29 # the risk of conflicts. We recommend you add at most one extension key,
30 # a dictionary which can contain all the values you need.
31
32
33 # Custom formatted extensions
34 GraphQLFormattedErrorExtensions = Dict[str, Any]
35 # Use a unique identifier name for your extension, for example the name of
36 # your library or project. Do not use a shortened identifier as this increases
37 # the risk of conflicts. We recommend you add at most one extension key,
38 # a dictionary which can contain all the values you need.
39
40
41 class GraphQLFormattedError(TypedDict, total=False):
42 """Formatted GraphQL error"""
43
44 # A short, human-readable summary of the problem that **SHOULD NOT** change
45 # from occurrence to occurrence of the problem, except for purposes of localization.
46 message: str
47 # If an error can be associated to a particular point in the requested
48 # GraphQL document, it should contain a list of locations.
49 locations: List["FormattedSourceLocation"]
50 # If an error can be associated to a particular field in the GraphQL result,
51 # it _must_ contain an entry with the key `path` that details the path of
52 # the response field which experienced the error. This allows clients to
53 # identify whether a null result is intentional or caused by a runtime error.
54 path: List[Union[str, int]]
55 # Reserved for implementors to extend the protocol however they see fit,
56 # and hence there are no additional restrictions on its contents.
57 extensions: GraphQLFormattedErrorExtensions
58
59
60 class GraphQLError(Exception):
61 """GraphQL Error
62
63 A GraphQLError describes an Error found during the parse, validate, or execute
64 phases of performing a GraphQL operation. In addition to a message, it also includes
65 information about the locations in a GraphQL document and/or execution result that
66 correspond to the Error.
67 """
68
69 message: str
70 """A message describing the Error for debugging purposes"""
71
72 locations: Optional[List["SourceLocation"]]
73 """Source locations
74
75 A list of (line, column) locations within the source GraphQL document which
76 correspond to this error.
77
78 Errors during validation often contain multiple locations, for example to point out
79 two things with the same name. Errors during execution include a single location,
80 the field which produced the error.
81 """
82
83 path: Optional[List[Union[str, int]]]
84 """
85
86 A list of field names and array indexes describing the JSON-path into the execution
87 response which corresponds to this error.
88
89 Only included for errors during execution.
90 """
91
92 nodes: Optional[List["Node"]]
93 """A list of GraphQL AST Nodes corresponding to this error"""
94
95 source: Optional["Source"]
96 """The source GraphQL document for the first location of this error
97
98 Note that if this Error represents more than one node, the source may not represent
99 nodes after the first node.
100 """
101
102 positions: Optional[Collection[int]]
103 """Error positions
104
105 A list of character offsets within the source GraphQL document which correspond
106 to this error.
107 """
108
109 original_error: Optional[Exception]
110 """The original error thrown from a field resolver during execution"""
111
112 extensions: Optional[GraphQLErrorExtensions]
113 """Extension fields to add to the formatted error"""
114
115 __slots__ = (
116 "message",
117 "nodes",
118 "source",
119 "positions",
120 "locations",
121 "path",
122 "original_error",
123 "extensions",
124 )
125
126 __hash__ = Exception.__hash__
127
128 def __init__(
129 self,
130 message: str,
131 nodes: Union[Collection["Node"], "Node", None] = None,
132 source: Optional["Source"] = None,
133 positions: Optional[Collection[int]] = None,
134 path: Optional[Collection[Union[str, int]]] = None,
135 original_error: Optional[Exception] = None,
136 extensions: Optional[GraphQLErrorExtensions] = None,
137 ) -> None:
138 super().__init__(message)
139 self.message = message
140
141 if path and not isinstance(path, list):
142 path = list(path)
143 self.path = path or None # type: ignore
144 self.original_error = original_error
145
146 # Compute list of blame nodes.
147 if nodes and not isinstance(nodes, list):
148 nodes = [nodes] # type: ignore
149 self.nodes = nodes or None # type: ignore
150 node_locations = (
151 [node.loc for node in nodes if node.loc] if nodes else [] # type: ignore
152 )
153
154 # Compute locations in the source for the given nodes/positions.
155 self.source = source
156 if not source and node_locations:
157 loc = node_locations[0]
158 if loc.source: # pragma: no cover else
159 self.source = loc.source
160 if not positions and node_locations:
161 positions = [loc.start for loc in node_locations]
162 self.positions = positions or None
163 if positions and source:
164 locations: Optional[List["SourceLocation"]] = [
165 source.get_location(pos) for pos in positions
166 ]
167 else:
168 locations = [loc.source.get_location(loc.start) for loc in node_locations]
169 self.locations = locations or None
170
171 if original_error:
172 self.__traceback__ = original_error.__traceback__
173 if original_error.__cause__:
174 self.__cause__ = original_error.__cause__
175 elif original_error.__context__:
176 self.__context__ = original_error.__context__
177 if extensions is None:
178 original_extensions = getattr(original_error, "extensions", None)
179 if isinstance(original_extensions, dict):
180 extensions = original_extensions
181 self.extensions = extensions or {}
182 if not self.__traceback__:
183 self.__traceback__ = exc_info()[2]
184
185 def __str__(self) -> str:
186 # Lazy import to avoid a cyclic dependency between error and language
187 from ..language.print_location import print_location, print_source_location
188
189 output = [self.message]
190
191 if self.nodes:
192 for node in self.nodes:
193 if node.loc:
194 output.append(print_location(node.loc))
195 elif self.source and self.locations:
196 source = self.source
197 for location in self.locations:
198 output.append(print_source_location(source, location))
199
200 return "\n\n".join(output)
201
202 def __repr__(self) -> str:
203 args = [repr(self.message)]
204 if self.locations:
205 args.append(f"locations={self.locations!r}")
206 if self.path:
207 args.append(f"path={self.path!r}")
208 if self.extensions:
209 args.append(f"extensions={self.extensions!r}")
210 return f"{self.__class__.__name__}({', '.join(args)})"
211
212 def __eq__(self, other: Any) -> bool:
213 return (
214 isinstance(other, GraphQLError)
215 and self.__class__ == other.__class__
216 and all(
217 getattr(self, slot) == getattr(other, slot)
218 for slot in self.__slots__
219 if slot != "original_error"
220 )
221 ) or (
222 isinstance(other, dict)
223 and "message" in other
224 and all(
225 slot in self.__slots__ and getattr(self, slot) == other.get(slot)
226 for slot in other
227 if slot != "original_error"
228 )
229 )
230
231 def __ne__(self, other: Any) -> bool:
232 return not self == other
233
234 @property
235 def formatted(self) -> GraphQLFormattedError:
236 """Get error formatted according to the specification.
237
238 Given a GraphQLError, format it according to the rules described by the
239 "Response Format, Errors" section of the GraphQL Specification.
240 """
241 formatted: GraphQLFormattedError = {
242 "message": self.message or "An unknown error occurred.",
243 }
244 if self.locations is not None:
245 formatted["locations"] = [location.formatted for location in self.locations]
246 if self.path is not None:
247 formatted["path"] = self.path
248 if self.extensions:
249 formatted["extensions"] = self.extensions
250 return formatted
251
252
253 def print_error(error: GraphQLError) -> str:
254 """Print a GraphQLError to a string.
255
256 Represents useful location information about the error's position in the source.
257 This deprecated helper is retained for backwards compatibility; call ``str(error)``
258 instead because ``print_error`` will be removed in v3.3.
259
260 .. deprecated:: 3.2
261 Please use ``str(error)`` instead. Will be removed in v3.3.
262 """
263 if not isinstance(error, GraphQLError):
264 raise TypeError("Expected a GraphQLError.")
265 return str(error)
266
267
268 def format_error(error: GraphQLError) -> GraphQLFormattedError:
269 """Format a GraphQL error.
270
271 Given a GraphQLError, format it according to the rules described by the "Response
272 Format, Errors" section of the GraphQL Specification. This deprecated helper is
273 retained for backwards compatibility; use ``error.formatted`` instead because
274 ``format_error`` will be removed in v3.3.
275
276 .. deprecated:: 3.2
277 Please use ``error.formatted`` instead. Will be removed in v3.3.
278 """
279 if not isinstance(error, GraphQLError):
280 raise TypeError("Expected a GraphQLError.")
281 return error.formatted