Skip to content
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

Django error formatter #392

Closed
Closed
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
19 changes: 19 additions & 0 deletions ariadne/contrib/django/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
FORMATTED_ERROR_MESSAGES: dict = {
"ValidationError": {"short": "Invalid input", "details": None,},
"ObjectDoesNotExist": {
"short": "Not found",
"details": "We were unable to locate the resource you requested.",
},
"NotAuthenticated": {
"short": "Unauthorized",
"details": "You are not currently authorized to make this request.",
},
"PermissionDenied": {
"short": "Forbidden",
"details": "You do not have permission to perform this action.",
},
"MultipleObjectsReturned": {
"short": "Multiple found",
"details": "Multiple resources were returned when only a single resource was expected",
},
}
114 changes: 114 additions & 0 deletions ariadne/contrib/django/format_error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import sys

import django.core.exceptions
from graphql import GraphQLError

try:
import rest_framework.exceptions
except ImportError:
pass

from ariadne import get_error_extension
from ariadne.contrib.django.constants import FORMATTED_ERROR_MESSAGES


def format_graphql_error(
error: GraphQLError,
error_field_name: str = "state",
constants: dict = None,
debug: bool = False,
) -> dict:
"""
We do not want to render arcane for-developer-only errors in the same way
we render user facing errors. So, we should use a custom field for
user-feedback related errors. We will well established patterns and
practices used by ValidationError in core django and django rest framework.
Any non-form errors will also be rendered in non_field_errors.
"""
if constants is None:
constants = FORMATTED_ERROR_MESSAGES

rest_framework_enabled = is_rest_framework_enabled()

formatted = error.formatted
original_error = extract_original_error(error)

if isinstance(original_error, django.core.exceptions.ValidationError):
formatted["message"] = constants["ValidationError"]["short"]
formatted[error_field_name] = get_full_django_validation_error_details(
original_error
)

elif rest_framework_enabled and isinstance(
original_error, rest_framework.exceptions.ValidationError
):
formatted["message"] = constants["ValidationError"]["short"]
formatted[error_field_name] = original_error.get_full_details()

elif isinstance(original_error, django.core.exceptions.ObjectDoesNotExist):
formatted["message"] = constants["ObjectDoesNotExist"]["short"]
formatted.setdefault(error_field_name, {})
formatted[error_field_name].setdefault("non_field_errors", [])
formatted[error_field_name]["non_field_errors"].append(
constants["ObjectDoesNotExist"]["details"]
)

elif rest_framework_enabled and isinstance(
original_error, rest_framework.exceptions.NotAuthenticated
):
formatted["message"] = constants["NotAuthenticated"]["short"]
formatted.setdefault(error_field_name, {})
formatted[error_field_name].setdefault("non_field_errors", [])
formatted[error_field_name]["non_field_errors"].append(
constants["NotAuthenticated"]["details"]
)

elif any(
[
isinstance(original_error, django.core.exceptions.PermissionDenied),
rest_framework_enabled
and isinstance(original_error, rest_framework.exceptions.PermissionDenied),
]
):
formatted["message"] = constants["PermissionDenied"]["short"]
formatted.setdefault(error_field_name, {})
formatted[error_field_name].setdefault("non_field_errors", [])
formatted[error_field_name]["non_field_errors"].append(
constants["PermissionDenied"]["details"]
)

elif isinstance(original_error, django.core.exceptions.MultipleObjectsReturned):
formatted["message"] = constants["MultipleObjectsReturned"]["short"]
formatted.setdefault(error_field_name, {})
formatted[error_field_name].setdefault("non_field_errors", [])
formatted[error_field_name]["non_field_errors"].append(
constants["MultipleObjectsReturned"]["details"]
)

if debug:
formatted.setdefault("extensions", {})
formatted["extensions"]["exception"] = get_error_extension(error)
return formatted


def extract_original_error(error: GraphQLError) -> Exception:
# Sometimes, ariadne nests the originally raised error. So, get to the bottom of it!
while getattr(error, "original_error", None):
error = getattr(error, "original_error")
return error


def get_full_django_validation_error_details(
error: django.core.exceptions.ValidationError,
) -> dict:
if getattr(error, "message_dict", None) is not None:
result = error.message_dict
elif getattr(error, "message", None) is not None:
result = {"non_field_errors": [error.message]}
else:
result = {"non_field_errors": error.messages}
return result


def is_rest_framework_enabled() -> bool:
return "rest_framework.exceptions" in sys.modules
1 change: 1 addition & 0 deletions requirements-dev.in
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
black
codecov
django<2.3
djangorestframework<3.12.0
freezegun
mypy
opentracing
Expand Down
10 changes: 8 additions & 2 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ chardet==3.0.4 # via requests
click==7.0 # via black, pip-tools
codecov==2.1.7 # via -r requirements-dev.in
coverage==4.5.4 # via codecov, pytest-cov
django==2.2.13 # via -r requirements-dev.in
django==2.2.13 # via -r requirements-dev.in, djangorestframework
djangorestframework==3.11.0 # via -r requirements-dev.in
fastdiff==0.2.0 # via snapshottest
freezegun==0.3.15 # via -r requirements-dev.in
idna==2.8 # via requests
importlib-metadata==1.6.1 # via pluggy, pytest
isort==4.3.21 # via pylint
lazy-object-proxy==1.4.3 # via astroid
mccabe==0.6.1 # via pylint
Expand Down Expand Up @@ -45,10 +47,14 @@ snapshottest==0.5.1 # via -r requirements-dev.in
sqlparse==0.3.0 # via django
termcolor==1.1.0 # via snapshottest
toml==0.10.0 # via black, pylint
typed-ast==1.4.0 # via black, mypy
typed-ast==1.4.0 # via astroid, black, mypy
typing-extensions==3.7.4.1 # via mypy
urllib3==1.25.7 # via requests
wasmer==0.3.0 # via fastdiff
wcwidth==0.1.7 # via pytest
werkzeug==1.0.1 # via -r requirements-dev.in
wrapt==1.11.2 # via astroid
zipp==3.1.0 # via importlib-metadata

# The following packages are considered to be unsafe in a requirements file:
# pip
Loading