【问题标题】:How to return customized JSON response for an error in django-graphene?如何为 django-graphene 中的错误返回自定义 JSON 响应?
【发布时间】:2018-05-17 11:05:11
【问题描述】:

我正在学习将 django-graphene 用于 graphql 目的。

对于突变,我只知道它会返回自己的错误消息。 假设我有一个令牌字段,并检查令牌字段是否坏,我只知道如何return None 这会给前端一个查询结果null 而不是自定义的状态和错误的json响应

我有这些代码

class ProductType(DjangoObjectType):
    class Meta:
        model = Product
        filter_fields = {'description': ['icontains']}
        interfaces = (graphene.relay.Node,)


class ProductInput(graphene.InputObjectType):
    token = graphene.String()
    title = graphene.String()
    barcode = graphene.String(required=True)


class CreateProduct(graphene.Mutation):
    class Arguments:
        product_input = ProductInput()

    product = graphene.Field(ProductType)

    def mutate(self, info, product_input=None):
        if not product_input.get('token'):
            return None  # instead of return None, I would like to return error code, status with message
        product = Product.objects.create(barcode=product_input.barcode, title=product_input.title)

        return CreateProduct(product=product)


class ProductMutation(graphene.ObjectType):
    create_product = CreateProduct.Field()

提前致谢

【问题讨论】:

    标签: django error-handling graphql mutation graphene-python


    【解决方案1】:

    您可以抛出异常,而不是 return None。异常将由石墨烯处理并作为错误传递。

    例如,raise Exception('Error 123456') 将产生类似

    的响应
    {
      "errors": [
        {
          "message": "Error 123456'",
          "locations": [
            {
              "line": 1,
              "column": 3
            }
          ]
        }
      ],
      "data": {
        "product": null
      }
    }
    

    输出 JSON 中存在errors 可以触发前端错误处理。

    请注意,一般情况下,传递给 graphql 的任何异常都将对外界可见,因此值得考虑所有石墨烯查询和突变异常的安全后果。

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 2021-01-08
      • 2021-07-13
      • 2020-04-23
      • 2020-11-27
      • 1970-01-01
      • 2021-11-07
      • 2016-08-30
      • 1970-01-01
      相关资源
      最近更新 更多