Skip to content

fix UnicodeDecodeError in format_error #223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions graphql/error/format_error.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from six import text_type

from .base import GraphQLError

# Necessary for static type checking
Expand All @@ -9,7 +7,12 @@

def format_error(error):
# type: (Exception) -> Dict[str, Any]
formatted_error = {"message": text_type(error)} # type: Dict[str, Any]
# Protect against UnicodeEncodeError when run in py2 (#216)
try:
message = str(error)
except UnicodeEncodeError:
message = error.message.encode("utf-8") # type: ignore
formatted_error = {"message": message} # type: Dict[str, Any]
if isinstance(error, GraphQLError):
if error.locations is not None:
formatted_error["locations"] = [
Expand Down
16 changes: 16 additions & 0 deletions graphql/execution/tests/test_format_error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# coding: utf-8
import pytest

from graphql.error import GraphQLError, format_error


@pytest.mark.parametrize(
"error",
[
GraphQLError("UNIÇODÉ!"),
GraphQLError("\xd0\xbe\xd1\x88\xd0\xb8\xd0\xb1\xd0\xba\xd0\xb0"),
],
)
def test_unicode_format_error(error):
# type: (GraphQLError) -> None
assert isinstance(format_error(error), dict)