Skip to content

Commit 8a88ab2

Browse files
committed
Deprecate print_error function
Replicates graphql/graphql-js@da685ee
1 parent 1f4c50a commit 8a88ab2

File tree

4 files changed

+74
-45
lines changed

4 files changed

+74
-45
lines changed

src/graphql/__init__.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -343,8 +343,7 @@
343343
GraphQLError,
344344
GraphQLSyntaxError,
345345
located_error,
346-
format_error,
347-
print_error,
346+
format_error
348347
)
349348

350349
# Utilities for operating on GraphQL type schema and parsed sources.
@@ -688,7 +687,6 @@
688687
"GraphQLSyntaxError",
689688
"located_error",
690689
"format_error",
691-
"print_error",
692690
"get_introspection_query",
693691
"get_operation_ast",
694692
"get_operation_root_type",

src/graphql/error/__init__.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
errors.
55
"""
66

7-
from .graphql_error import GraphQLError, format_error, print_error
7+
from .graphql_error import GraphQLError, format_error
88

99
from .syntax_error import GraphQLSyntaxError
1010

@@ -14,6 +14,5 @@
1414
"GraphQLError",
1515
"GraphQLSyntaxError",
1616
"format_error",
17-
"located_error",
18-
"print_error",
17+
"located_error"
1918
]

src/graphql/error/graphql_error.py

Lines changed: 43 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from ..language.location import SourceLocation # noqa: F401
77
from ..language.source import Source # noqa: F401
88

9-
__all__ = ["GraphQLError", "format_error", "print_error"]
9+
__all__ = ["GraphQLError"]
1010

1111

1212
class GraphQLError(Exception):
@@ -137,7 +137,21 @@ def __init__(
137137
self.__traceback__ = exc_info()[2]
138138

139139
def __str__(self) -> str:
140-
return print_error(self)
140+
# Lazy import to avoid a cyclic dependency between error and language
141+
from ..language.print_location import print_location, print_source_location
142+
143+
output = [self.message]
144+
145+
if self.nodes:
146+
for node in self.nodes:
147+
if node.loc:
148+
output.append(print_location(node.loc))
149+
elif self.source and self.locations:
150+
source = self.source
151+
for location in self.locations:
152+
output.append(print_source_location(source, location))
153+
154+
return "\n\n".join(output)
141155

142156
def __repr__(self) -> str:
143157
args = [repr(self.message)]
@@ -173,49 +187,47 @@ def __ne__(self, other: Any) -> bool:
173187

174188
@property
175189
def formatted(self) -> Dict[str, Any]:
176-
"""Get error formatted according to the specification."""
177-
return format_error(self)
190+
"""Get error formatted according to the specification.
191+
192+
Given a GraphQLError, format it according to the rules described by the
193+
"Response Format, Errors" section of the GraphQL Specification.
194+
"""
195+
formatted: Dict[str, Any] = dict( # noqa: E701 (pycqa/flake8#394)
196+
message=self.message or "An unknown error occurred.",
197+
locations=(
198+
[location.formatted for location in self.locations]
199+
if self.locations is not None
200+
else None
201+
),
202+
path=self.path,
203+
)
204+
if self.extensions:
205+
formatted.update(extensions=self.extensions)
206+
return formatted
178207

179208

180209
def print_error(error: GraphQLError) -> str:
181210
"""Print a GraphQLError to a string.
182211
183212
Represents useful location information about the error's position in the source.
184-
"""
185-
# Lazy import to avoid a cyclic dependency between error and language
186-
from ..language.print_location import print_location, print_source_location
187-
188-
output = [error.message]
189213
190-
if error.nodes:
191-
for node in error.nodes:
192-
if node.loc:
193-
output.append(print_location(node.loc))
194-
elif error.source and error.locations:
195-
source = error.source
196-
for location in error.locations:
197-
output.append(print_source_location(source, location))
198-
199-
return "\n\n".join(output)
214+
.. deprecated:: 3.2
215+
Please use ``str(error)`` instead. Will be removed in v3.3.
216+
"""
217+
if not isinstance(error, GraphQLError):
218+
raise TypeError("Expected a GraphQLError.")
219+
return str(error)
200220

201221

202222
def format_error(error: GraphQLError) -> Dict[str, Any]:
203223
"""Format a GraphQL error.
204224
205225
Given a GraphQLError, format it according to the rules described by the "Response
206226
Format, Errors" section of the GraphQL Specification.
227+
228+
.. deprecated:: 3.2
229+
Please use ``error.formatted`` instead. Will be removed in v3.3.
207230
"""
208231
if not isinstance(error, GraphQLError):
209232
raise TypeError("Expected a GraphQLError.")
210-
formatted: Dict[str, Any] = dict( # noqa: E701 (pycqa/flake8#394)
211-
message=error.message or "An unknown error occurred.",
212-
locations=(
213-
[location.formatted for location in error.locations]
214-
if error.locations is not None
215-
else None
216-
),
217-
path=error.path,
218-
)
219-
if error.extensions:
220-
formatted.update(extensions=error.extensions)
221-
return formatted
233+
return error.formatted

tests/error/test_graphql_error.py

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
from typing import cast, List, Union
22

3-
from graphql.error import GraphQLError, print_error
3+
from pytest import raises
4+
5+
from graphql.error import GraphQLError
46
from graphql.language import (
57
parse,
68
OperationDefinitionNode,
@@ -129,16 +131,26 @@ def serializes_to_include_message_and_locations():
129131
assert repr(e) == (
130132
"GraphQLError('msg', locations=[SourceLocation(line=2, column=3)])"
131133
)
134+
assert e.formatted == {
135+
"locations": [{"column": 3, "line": 2}],
136+
"message": "msg",
137+
"path": None,
138+
}
132139

133140
def repr_includes_extensions():
134141
e = GraphQLError("msg", extensions={"foo": "bar"})
135-
assert repr(e) == ("GraphQLError('msg', extensions={'foo': 'bar'})")
142+
assert repr(e) == "GraphQLError('msg', extensions={'foo': 'bar'})"
136143

137144
def serializes_to_include_path():
138145
path: List[Union[int, str]] = ["path", 3, "to", "field"]
139146
e = GraphQLError("msg", path=path)
140147
assert e.path is path
141148
assert repr(e) == "GraphQLError('msg', path=['path', 3, 'to', 'field'])"
149+
assert e.formatted == {
150+
"locations": None,
151+
"message": "msg",
152+
"path": ["path", 3, "to", "field"],
153+
}
142154

143155
def always_stores_path_as_list():
144156
path: List[Union[int, str]] = ["path", 3, "to", "field"]
@@ -171,17 +183,27 @@ def hashes_are_unique_per_instance():
171183
assert hash(e1) != hash(e2)
172184

173185

174-
def describe_print_error():
186+
def describe_to_string():
187+
def deprecated_prints_an_error_using_print_error():
188+
# noinspection PyProtectedMember
189+
from graphql.error.graphql_error import print_error
190+
error = GraphQLError("Error")
191+
assert print_error(error) == "Error"
192+
with raises(TypeError) as exc_info:
193+
# noinspection PyTypeChecker
194+
print_error(Exception) # type: ignore
195+
assert str(exc_info.value) == "Expected a GraphQLError."
196+
175197
def prints_an_error_without_location():
176198
error = GraphQLError("Error without location")
177-
assert print_error(error) == "Error without location"
199+
assert str(error) == "Error without location"
178200

179201
def prints_an_error_using_node_without_location():
180202
error = GraphQLError(
181203
"Error attached to node without location",
182204
parse("{ foo }", no_location=True),
183205
)
184-
assert print_error(error) == "Error attached to node without location"
206+
assert str(error) == "Error attached to node without location"
185207

186208
def prints_an_error_with_nodes_from_different_sources():
187209
doc_a = parse(
@@ -221,8 +243,7 @@ def prints_an_error_with_nodes_from_different_sources():
221243
"Example error with two nodes", [field_a.type, field_b.type]
222244
)
223245

224-
printed_error = print_error(error)
225-
assert printed_error == dedent(
246+
assert str(error) == dedent(
226247
"""
227248
Example error with two nodes
228249
@@ -239,4 +260,3 @@ def prints_an_error_with_nodes_from_different_sources():
239260
3 | }
240261
"""
241262
)
242-
assert str(error) == printed_error

0 commit comments

Comments
 (0)