graphql-api
graphql-api copied to clipboard
Domain errors on Mutations
First of all thanks for putting all the effort into this library.
What is the correct way to represent errors that belong to my application, not GraphQL related? Stuff like Email already exists
in a signup
mutation, or validation errors like Name should contain at least 2 characters
?
Also, if you are looking for contributors, I would be happy to help. It would be nice to start tackling some easy stuff first and then grow to bigger problems.
Thanks!
Hi, this is a very good question, albeit mostly unrelated to the library IMHO.
You pointed out already that there is a natural distinction between domain errors and technical errors. We made good experience by modeling domain errors in the Graph itself. Clients usually want to display those in some form to the user whichis is rather tedious if you have to extract those from the errors field in the GraphQL response.
How you actually model it is up to you but I think you want to have the following properties:
- if the mutation failed with a domain error you want to stop execution at that level
- you likely want typed errors
- if all went well you want to just continue traversing the graph
One good way to do it seems to be a union type.
type SuccessData {
name: String
lastName: String
friends: SomeEdge
}
type ErrorData {
errors: [String] # you likely want better types here
}
union MyMutationResult = SuccessData | ErrorData
extend type Mutation {
myMutation: MutationResult
}
This could be used like this:
mutation DoIt {
myMutation {
... on SuccessData { name lastName }
... on ErrorData { errors }
}
}
Error representation is still one of the weak spots in GraphQL. So what I said is not a „standard“ way of doing things but rather the learnings me and my team have after having built, evolved and operated our GraphQL gateway in production for the last ~2years. We actually don’t use unions but specialised execution that is turned on with directives but the underlying idea remains the same.