haskell-graphql / graphql-api

Write type-safe GraphQL services in Haskell
BSD 3-Clause "New" or "Revised" License
406 stars 35 forks source link

Domain errors on Mutations #200

Open thiagorp opened 6 years ago

thiagorp commented 6 years ago

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!

certainty commented 5 years ago

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:

  1. if the mutation failed with a domain error you want to stop execution at that level
  2. you likely want typed errors
  3. 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.