How to handle Errors with the Apollo stack
Asked Answered
P

1

10

I'm using the Apollo Stack with graphql-server-express and apollo-client.

Because my backend is not perfect errors can appear and therefore I have to respond to a request with an error for that path.

Till now my main problem was authentication and therefore I responded with an error.

return new Error(`${data.status}: ${data.statusText} @ ${data.url}`)

In the frontend I use apollo-client to query data.

return apollo
        .query({query: gql`
            query {
                ${query}
            }`,
            forceFetch: forceFetch
        })
        .then(result => { debugger; return result.data })
        .catch(error => { debugger; console.error(error); });

But if one property of the query responds with an error, only the catch function will be invoked. Even the data of the remaining properties is transferred, I see this in the network tab of the Chrome Dev Tools. In is not error object in the catch function.

My attempt works fine with GraphiQL where I get the errors and data in the same object.

So how can I throw errors for a property without loosing the whole request?

Psalmbook answered 25/1, 2017 at 13:29 Comment(0)
P
0

You could manually look for result.error in the then part of your promise and avoid the use of catch. Also I think you could also add a then after the catch call to handle this specific case.

In addition to that, you can also use formatError in your GraphQL server to manually filter and format error messages. The body of that function is the following, and you have access to the thrown Error.

formatError: (error) => {
  return {
    name: error.name,
    mensaje: error.message
  }
}
Petaliferous answered 2/7, 2017 at 22:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.