From fb749253e9a7bea950db1ab3d27eb95d97bde9ac Mon Sep 17 00:00:00 2001 From: chinskiy Date: Tue, 12 Mar 2019 20:39:42 +0200 Subject: [PATCH] fix UnicodeDecodeError in format_error #216 --- graphql/error/format_error.py | 9 ++++++--- graphql/execution/tests/test_format_error.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 graphql/execution/tests/test_format_error.py diff --git a/graphql/error/format_error.py b/graphql/error/format_error.py index fd162c82..a854095b 100644 --- a/graphql/error/format_error.py +++ b/graphql/error/format_error.py @@ -1,5 +1,3 @@ -from six import text_type - from .base import GraphQLError # Necessary for static type checking @@ -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"] = [ diff --git a/graphql/execution/tests/test_format_error.py b/graphql/execution/tests/test_format_error.py new file mode 100644 index 00000000..67a75f40 --- /dev/null +++ b/graphql/execution/tests/test_format_error.py @@ -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)