graphql-python / graphene

GraphQL framework for Python
http://graphene-python.org/
MIT License
8.1k stars 828 forks source link

Returning non fatal errors alongside data #1536

Closed yairsilbermintz-aon closed 5 months ago

yairsilbermintz-aon commented 10 months ago

I have a mutation that updates multiple records. In cases where some of the records would be invalid, I want to skip updating those records, update what records I can, and return a list of the ones that failed in the errors array

GraphQL has support for returning a partial response along with non fatal error information. Graphene already uses this in certain cases, such as an error accessing a specific subfield in a request.

There are docs for [https://docs.graphene-python.org/projects/django/en/latest/mutations/#simple-example](returning data from a successful mutation), and it is easy to return an error by raising an exception. But is there any way for me to return both from my mutation?

erikwrede commented 5 months ago

Hey there, the pattern you're looking for is user errors / schema defined errors. Basically, you don't want to raise an exception but include the error information in your schema response. Some common patterns are listed here, which you can all build using graphene 🙂 https://productionreadygraphql.com/2020-08-01-guide-to-graphql-errors

Returning data alongside an error in the same field is not possible due to the way GraphQL works. A field resolver either returns the data, null, or an error. If a field is nullable and an error was thrown, the entire subtree of this field will be dropped from the response. If the field is not nullable, the error will bubble up to the next nullable node (the root data node is always nullable if no previous node was nullable), setting all child data to null along the way. You can learn more about error bubbling here https://www.apollographql.com/docs/kotlin/essentials/errors