I'm having a trouble with Graphql and Apollo Client.
I always created differents responses like 401 code when I using REST but here I don't know how I to do a similar behavior.
When I get the response I want it go to the catch function. I have this code in the front:
client.query({
query: gql`
query TodoApp {
todos {
id
text
completed
}
}
`,
})
.then(data => console.log(data))
.catch(error => console.error(error));
Can anybody help me?
The way to return errors in GraphQL (at least in graphql-js) is to throw errors inside the resolve functions. Because HTTP status codes are specific to the HTTP transport and GraphQL doesn't care about the transport, there's no way for you to set the status code there. What you can do instead is throw a specific error inside your resolve function:
GraphQL errors get sent to the client in the response like so:
If the message is not enough information, you could create a special error class for your GraphQL server which includes a status code. To make sure that status code gets included in your response, you'll have to specify the
formatError
function when creating the middleware:Just to complement Glenn's answer, here is the part of Graphql Spec that defines how errors should be handled. So to know if the request failed (or partially failed) your can check for the "errors" key at the root of the response.
There has been a recent addition to the spec concerning errors outputs:
Now using the
extensions
field you can custom machine-readable information to yourerrors
entries:Latest version of Apollo-Server is spec-compliant with this feature check it out Here.