is there a best practice on how to return an error (validation for mutation or otherwise) I have been trying the various workarounds suggested in the issues section to no avail :(
I am hoping for something as simple returning status_code=400 for bad request and a list of errors to the front end
I made it subclassing GraphQLView and overriding format_error method.
Something like
class CustomGraphQLView(GraphQLView):
@staticmethod
def format_error(error):
if hasattr(error, 'original_error') and error.original_error:
formatted = {"message": str(error.original_error)}
if isinstance(error.original_error, UnauthorizedError):
formatted['code'] = "401"
elif isinstance(error.original_error, PermissionDeniedError):
formatted['code'] = "403"
return formatted
return GraphQLView.format_error(error)
PermissonDeniedError and UnauthorizedError are custom exceptions in our project.
It works only for single error though.
As far as I know, any uncaught Exception raised during query validation or execution will cause the graphql response to return 400, and the Exception will be coerced into a str and put in the errors key like "errors": [{"message": "Exception as string"}].
Is there something more specific you need, or is that not working as expected in some cases?
For auth errors is better to return 401 and 403
The small plugin graphene-django-sentry has an example where it captures errors before returning, I'd suggest looking at that and adapting it for your needs.
Most helpful comment
I made it subclassing
GraphQLViewand overridingformat_errormethod.Something like
PermissonDeniedErrorandUnauthorizedErrorare custom exceptions in our project.It works only for single error though.