djangographqlgraphene-djangographql-mutation

How can I can not raise error in mutations with graphene django?


I'm using graphene-django-cud for mutations. But I can't raise any GraphQLError, ValueError or Exception in mutations. Like in before_mutate() or any validate_ method. The process just stop with out any error message. Then return null for the instance and message.

@classmethod
def before_mutate(cls, root, info, input, id):
    print("before_mutate")
    from graphql import GraphQLError
    raise GraphQLError(f"The observation with id {id} doesn't exists")

@classmethod
def validate_name(cls, root, info, value, input, id, obj):
    print("validate_name")
    raise ValueError(f"The observation with id {id} doesn't existssss")

Anyone met this before? Thanks in advance!


Solution

  • Now I figured out what's going on.

    It's not from graphene-django-cud, it's from graphene. I have to add try/except to catch the error, then return a GraphQLError.

    from graphene import Field
    from graphene_django_cud.mutations import DjangoCreateMutation
    from graphql import GraphQLError
    from .models import Demo
    from .types import DemoType
    import logging
    import traceback
    
    class DemoCreateMutation(DjangoCreateMutation):
        demo = Field(DemoType)
    
        class Meta:
            model = Demo
    
        @classmethod
        def mutate(cls, root, info, input):
            try:
                return super().mutate(root, info, input)
            except Exception as e:
                logging.error(str(e))
                return GraphQLError(traceback.format_exc())
    
        @classmethod
        def before_mutate(cls, root, info, input, id):
            raise GraphQLError(f"The Demo {id} doesn't exists")
    
        @classmethod
        def validate_name(cls, root, info, value, input, id, obj):
            raise ValueError(f"The Demo {id} doesn't existssss")