Skip to content

Commit

Permalink
custom error class
Browse files Browse the repository at this point in the history
  • Loading branch information
JerrySentry committed Nov 19, 2024
1 parent 0a625dd commit 12ee4f3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
19 changes: 14 additions & 5 deletions graphql_api/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@
from graphql.validation import ValidationContext


class MissingVariablesError(Exception):
"""
Custom error class to represent errors where required variables defined in the query does
not have a matching definition in the variables part of the request. Normally when this
scenario occurs it would raise a GraphQLError type but that would cause a uncaught
exception for some reason. The aim of this is to surface the error in the response clearly
and to prevent internal server errors when it occurs.
"""

pass


def create_required_variables_rule(variables: Dict) -> Type[ValidationRule]:
class RequiredVariablesValidationRule(ValidationRule):
def __init__(self, context: ValidationContext) -> None:
Expand Down Expand Up @@ -50,11 +62,8 @@ def enter_operation_definition(
]
print("missing_variables", missing_variables)
if missing_variables:
self.report_error(
GraphQLError(
f"Missing required variables: {', '.join(missing_variables)}",
node,
)
raise MissingVariablesError(
f"Missing required variables: {', '.join(missing_variables)}",
)

return RequiredVariablesValidationRule
Expand Down
16 changes: 11 additions & 5 deletions graphql_api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

from .schema import schema
from .validation import (
MissingVariablesError,
create_max_aliases_rule,
create_max_depth_rule,
create_required_variables_rule,
Expand Down Expand Up @@ -264,16 +265,21 @@ async def post(self, request, *args, **kwargs):
)

with RequestFinalizer(request):
print("About to make request")
response = await super().post(request, *args, **kwargs)
print("Finished request")
try:
response = await super().post(request, *args, **kwargs)
except MissingVariablesError as e:
return JsonResponse(
data={
"status": 400,
"detail": str(e),
},
status=400,
)

content = response.content.decode("utf-8")
data = json.loads(content)

print("Are there errors?", data)
if "errors" in data:
print("Yes there is")
inc_counter(
GQL_ERROR_TYPE_COUNTER,
labels=dict(error_type="all", path=req_path),
Expand Down

0 comments on commit 12ee4f3

Please sign in to comment.