mirror of
https://github.com/graphql-python/graphene-django.git
synced 2025-07-14 02:02:20 +03:00
docs: document how custom error formatting works
This commit is contained in:
parent
f76f38ef30
commit
08a42961da
51
docs/custom-errors.rst
Normal file
51
docs/custom-errors.rst
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
Custom errors
|
||||||
|
=============
|
||||||
|
|
||||||
|
Default GraphQL error format similar to the following snippet
|
||||||
|
|
||||||
|
.. code: json
|
||||||
|
|
||||||
|
{
|
||||||
|
"errors": [
|
||||||
|
{
|
||||||
|
"message": "Variable \"$myAwesomeField\" of required type \"String!\" was not provided.",
|
||||||
|
"locations": [
|
||||||
|
{
|
||||||
|
"line": 1,
|
||||||
|
"column": 13
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
And there is a way customise it by swapping default ``GraphQLView`` with your own
|
||||||
|
and then override ``format_error`` method
|
||||||
|
|
||||||
|
.. code: python
|
||||||
|
class MyGraphQLView(GraphQLView):
|
||||||
|
@staticmethod
|
||||||
|
def format_error(error) -> Dict[str, Any]:
|
||||||
|
if isinstance(error, GraphQLError):
|
||||||
|
return format_error(error)
|
||||||
|
|
||||||
|
return GraphQLView.format_error(error)
|
||||||
|
|
||||||
|
|
||||||
|
Here is custom formatting function
|
||||||
|
|
||||||
|
.. code: python
|
||||||
|
def format_error(error: GraphQLError) -> Dict[str, Any]:
|
||||||
|
"""Extract field from ``error`` and return formatted error
|
||||||
|
:param error: GraphQLError
|
||||||
|
:return: mapping of fieldName -> error message
|
||||||
|
"""
|
||||||
|
formatted_error = {
|
||||||
|
n.variable.name.value: str(error)
|
||||||
|
for n in error.nodes
|
||||||
|
}
|
||||||
|
|
||||||
|
if error.path:
|
||||||
|
formatted_error["path"] = error.path
|
||||||
|
|
||||||
|
return formatted_error
|
|
@ -13,4 +13,4 @@ Contents:
|
||||||
debug
|
debug
|
||||||
rest-framework
|
rest-framework
|
||||||
form-mutations
|
form-mutations
|
||||||
introspection
|
custom-errors
|
||||||
|
|
Loading…
Reference in New Issue
Block a user