Debian Codegraph @

src/graphql/error/located_error.py

raw
1 from typing import TYPE_CHECKING, Collection, Optional, Union
2
3 from ..pyutils import inspect
4 from .graphql_error import GraphQLError
5
6 if TYPE_CHECKING:
7 from ..language.ast import Node # noqa: F401
8
9 __all__ = ["located_error"]
10
11
12 def located_error(
13 original_error: Exception,
14 nodes: Optional[Union["None", Collection["Node"]]] = None,
15 path: Optional[Collection[Union[str, int]]] = None,
16 ) -> GraphQLError:
17 """Located GraphQL Error
18
19 Given an arbitrary Exception, presumably thrown while attempting to execute a
20 GraphQL operation, produce a new GraphQLError aware of the location in the document
21 responsible for the original Exception.
22 """
23 # Sometimes a non-error is thrown, wrap it as a TypeError to ensure consistency.
24 if not isinstance(original_error, Exception):
25 original_error = TypeError(f"Unexpected error value: {inspect(original_error)}")
26 # Note: this uses a brand-check to support GraphQL errors originating from
27 # other contexts.
28 if isinstance(original_error, GraphQLError) and original_error.path is not None:
29 return original_error
30 try:
31 # noinspection PyUnresolvedReferences
32 message = str(original_error.message) # type: ignore
33 except AttributeError:
34 message = str(original_error)
35 try:
36 # noinspection PyUnresolvedReferences
37 source = original_error.source # type: ignore
38 except AttributeError:
39 source = None
40 try:
41 # noinspection PyUnresolvedReferences
42 positions = original_error.positions # type: ignore
43 except AttributeError:
44 positions = None
45 try:
46 # noinspection PyUnresolvedReferences
47 nodes = original_error.nodes or nodes # type: ignore
48 except AttributeError:
49 pass
50 return GraphQLError(message, nodes, source, positions, path, original_error)