graphql-python / graphql-python/graphene

Typed Errors and Graphene

Abierto
#1,427 10 comentarios 1 reacción 0 asignados Ver en GitHub
✨ enhancement
Lenguaje dominante
Python
Estrellas
8.2k
Forks
818
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

Hi folks,

I'm raising this issue to gauge ideas from the Python community on error handling best practices.

The usual way to handle errors in GraphQL is by inspecting the top-level `errors` key:

```json
{
"errors": {
# ... your error details ...
},
"data": null
}
```

However, this is usually problematic for API clients as they don't know **what to expect** from this `errors` key.
This means that error **discoverability** is impacted.

Another downside, is that the `data` key must be null when these high-level errors are raised.
In many situations API clients are interested in calling a mutation and, even if it fails, they'd like to receive data back. This data can be anything, but it's usually the object being mutated itself.

Another approach is extending upon this idea of typed errors that is strongly supported by Lee Byron as you can see [here](https://github.com/graphql/graphql-spec/issues/391#issuecomment-385553207).

This seems to solve both problems above (along with many others). Here's my take on what this would look like in Graphene:

```python
class ErrorInterface(graphene.Interface):
message = graphene.NonNull(graphene.String)

class ThingAErrorType(graphene.ObjectType):
class Meta:
interfaces = [ErrorInterface]

class ThingBErrorType(graphene.ObjectType):
class Meta:
interfaces = [ErrorInterface]

class MySweetMutationErrorUnion(graphene.Union):
class Meta:
types = [ThingAErrorType, ThingBErrorType]

class MySweetMutation():
error = graphene.Field(MySweetMutationErrorUnion)
output = graphene.Field(MySweetOutputType)

def mutate(self, info, input):
try:
thing_a = do_thing_a(input)
except ThingAException:
return MySweetMutation(error=ThingAErrorType())
try:
thing_b = do_thing_b(input)
except ThingBException:
return MySweetMutation(error=ThingBErrorType())
# happy path!
output = MySweetOutputType(thing_a=thing_a, thing_b=thing_b)
return MySweetMutation(output=output)
```

If we have a look at what the schema looks like, we have this:

![image](https://user-images.githubusercontent.com/17491689/174235028-f227ebfd-47cf-48ba-9826-9c00ba2aef8e.png)

![image](https://user-images.githubusercontent.com/17491689/174235275-1ade5ae5-c46c-426f-ae2a-248e882e7bf8.png)

And finally, API clients can query this mutation like this:

```graphql
mutation mySweetMutation($input: MySweetMutationInput!) {
mySweetMutation(input: $input) {
output {
# ....
}
error {
... on ThingAError {
__typename
message
}
... on ThingBError {
__typename
message
}
# We have an interface here so that we
# can extend the union with more errors without breaking
# backwards compatibility!!
__typename
message
}
}
}
```

I'm interested in your thoughts in this approach.
Thanks!

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Línea de trabajo

No se nombran archivos del repositorio, pruebas ni puntos de entrada. Empieza revisando el ErrorInterface, el error union y la mutation shape propuestos en el issue; después, aclara con los maintainers si esto debe documentarse o implementarse y qué criterios de aceptación definirían la finalización.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
graphql, python
Área
api, backend
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.