Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 804
mango parade Avatar asked Mar 01 '16 03:03

mango parade


People also ask

How do you handle errors in Apollo?

On GraphQL errorsThe onError link can retry a failed operation based on the type of GraphQL error that's returned. For example, when using token-based authentication, you might want to automatically handle re-authentication when the token expires. // instead of the onError link. This just logs the error.

What is Apollo boost?

Apollo Boost is a zero-config way to start using Apollo Client. It includes some sensible defaults, such as our recommended InMemoryCache and HttpLink , which come configured for you with our recommended settings.

What does useMutation return?

When your component renders, useMutation returns a tuple that includes: A mutate function that you can call at any time to execute the mutation. Unlike useQuery , useMutation doesn't execute its operation automatically on render. Instead, you call this mutate function.


1 Answers

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.

like image 64
devric Avatar answered Nov 26 '22 11:11

devric