2017-12-04 17 views
0

グラフの目的にdjango-grapheneを使用する方法を学んでいます。django-grapheneのエラーに対するカスタマイズされたJSONレスポンスを返すには?

突然変異については、それ自身のエラーメッセージが返されることがわかっています。 のトークンフィールドが悪い場合、私はトークンのフィールドを持っている、と確認した場合、私は唯一のフロントエンドにnullのクエリ結果を与えることになるかとreturn None知っているとしましょう代わりにステータスとエラー

のためのカスタマイズされたJSONレスポンスのIは、これらのコードにあなたが例外をスローすることができ、事前

答えて

1

代わりのreturn None

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() 

感謝を持っています。例外はgrapheneによって処理され、エラーとして渡されます。例えば

raise Exception('Error 123456')は、JSONは、フロントエンドエラー処理をトリガすることができる出力に応答して

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

ようなものerrorsの存在をもたらします。

一般的に、graphqlに渡された例外はすべて外部から見えるので、グラフェンクエリと突然変異例外のセキュリティの影響を検討する価値があります。

関連する問題