mango parade
mango parade

Reputation: 143

Handling errors in mutations

Let's say I'm trying to create a bike as a mutation

var createBike = (wheelSize) => {
  if (!factoryHasEnoughMetal(wheelSize)) {
    return supplierError('Not enough metal');
  }
  return factoryBuild(wheelSize);
}

What happens when there's not enough steel for them shiny wheels? We'll probably need an error for the client side. How do I get that to them from my graphQL server with the below mutation:

// Mutations
mutation: new graphql.GraphQLObjectType({
  name: 'BikeMutation',
  fields: () => ({
    createBike: {
      type: bikeType,
      args: {
        wheelSize: {
          description: 'Wheel size',
          type: new graphql.GraphQLNonNull(graphql.Int)
        },
      },
      resolve: (_, args) => createBike(args.wheelSize)
    }
  })
})

Is it as simple as returning some error type which the server/I have defined?

Upvotes: 5

Views: 5862

Answers (1)

devric
devric

Reputation: 3675

Not exactly sure if this is what you after...

Just throw a new error, it should return something like

{
  "data": {
    "createBike": null
  },
  "errors": [
    {
      "message": "Not enough metal",
      "originalError": {}
    }
  ]
}

your client side should just handle the response

if (res.errors) {res.errors[0].message}

What I do is passing a object with errorCode and message, at this stage, the best way to do is stringify it.

throw new Errors(JSON.stringify({
      code:409, 
      message:"Duplicate request......"
}))

NOTE: also you might be interested at this library https://github.com/kadirahq/graphql-errors

you can mask all errors (turn message to "Internal Error"), or define userError('message to the client'), which these will not get replaced.

Upvotes: 7

Related Questions