graphene-django icon indicating copy to clipboard operation
graphene-django copied to clipboard

How to customise mutation validation error messages

Open sultaniman opened this issue 7 years ago • 13 comments

Hi,

I've been trying to customise mutation validation errors but so far didn't succeed in doing so, having the following query I would like to be able to return errors if different shape

mutation CreateProject($projectName: String!, $description: String!) {
  createProject(projectName: $projectName, description: $description) {
    id
    projectName
    description
  }
}

Standard errors look like

{
  "errors": [
    {
      "message": "Variable \"$description\" of required type \"String!\" was not provided.",
      "locations": [
        {
          "line": 1,
          "column": 47
        }
      ]
    }
  ]
}

What I would like to have is

{
  "errors": [
    {
        "$description": "Error message...",
        "locations": [...]
    }
}

So is it possible to adjust error response format?

Thanks.

sultaniman avatar Oct 30 '18 20:10 sultaniman

Yup, it is possible, I haven't tried but it should be here: https://github.com/graphql-python/graphene-django/blob/master/graphene_django/views.py#L176-L179

Let me know if that works!

patrick91 avatar Oct 31 '18 13:10 patrick91

@patrick91 thanks for information. I tried to look into tests to see some examples but didn't find one. Does the logic mean that I have to manually validate or override GraphQLView?

Thanks.

sultaniman avatar Oct 31 '18 13:10 sultaniman

Yes, I think so :)

I would do:

from graphene_django.views import GraphQLView

class MyGraphQLView(GraphQLView):
    def format_error(self, error):
        return 'ABC'

That should work, sorry I can't test this right now!

patrick91 avatar Oct 31 '18 14:10 patrick91

@patrick91 no worries, thank you very much for your time! I will definitely try it out.

sultaniman avatar Oct 31 '18 14:10 sultaniman

Let me know, might be worth to add something to the docs about this :)

patrick91 avatar Oct 31 '18 14:10 patrick91

@patrick91 I've been thinking about making a PR which documents this feature.

sultaniman avatar Oct 31 '18 14:10 sultaniman

So I managed to make it and here is my solution

Custom view

from typing import Any, Dict

from graphene_django.views import GraphQLView
from graphql.error import GraphQLError

from graph.format_error import format_error


class MyGraphQLView(GraphQLView):
    @staticmethod
    def format_error(error) -> Dict[str, Any]:
        if isinstance(error, GraphQLError):
            return format_error(error)

        return GraphQLView.format_error(error)

Error formatter

from typing import Dict, Any

from graphql import GraphQLError


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 = {
        e.variable.name.value: str(e)
        for e in error.nodes
    }

    if error.path:
        formatted_error["path"] = error.path

    return formatted_error

sultaniman avatar Oct 31 '18 21:10 sultaniman

@patrick91 documentation related question is where to add notion about custom error formatting? By the way is it planned to use gettext in graphql-core to have localised error messages?

Thanks.

sultaniman avatar Oct 31 '18 21:10 sultaniman

@imanhodjaev not sure, maybe we could create another page just for that :)

By the way is it planned to use gettext in graphql-core to have localised error messages?

Good question, @syrusakbary I think this one is for you ;)

patrick91 avatar Nov 01 '18 14:11 patrick91

@patrick91 cool then I will create a page for it.

sultaniman avatar Nov 01 '18 15:11 sultaniman

Closing as resolved, adding as a potential docs enhancement

phalt avatar Apr 26 '19 11:04 phalt

Looking forward for the doc section regarding customization of error messages.

KingDarBoja avatar Feb 06 '20 22:02 KingDarBoja

Closing as resolved, adding as a potential docs enhancement

Is this closed because there is a new issue? If not, let me know if you'd like me to create a new issue specific to docs enhancement.

mcabrams avatar May 28 '20 19:05 mcabrams