9. Errors! When something goes wrong

Our Catstronauts app development has been going pretty smoothly. But we know that things don't always go that way in the real world.

There are more than a few ways things can go wrong. In our journey, when the server is validating the query AST against the schema, it could run into invalid or malformed selections. With that, the query's journey is cut short and returned to client-land with errors.

Hand-drawn illustration depicting a GraphQL server returning an error to client-land because of malformed queries

Let's look at an example where we try to for the numberOfViews , because we want to add that piece of data to our tracks card on the homepage. We know that it exists in our because we even saw the /tracks endpoint return it!

That is true, but the numberOfViews is not a part of our . And if we try to add it to the , the Explorer shows us with a helpful red squiggly that something is wrong with our query.

Screenshot of Apollo Studio Explorer showing an invalid field, `numberOfViews`, underlined by a red squiggly line

We can still attempt to run the , and it will start its journey. But that journey will be cut short at the server validation step, at which point the server will send back its response.

In the response, we'll see a new key: errors.

Screenshot of Apollo Studio Explorer showing the error we get in response to submitting a query with an invalid field
Code Challenge!

In the Explorer of Apollo Sandbox, replace all selected fields inside tracksForHome with just "numberOfViews". Copy-paste the whole response below.

errors is an array containing each error that occurred as the server tried to execute the . So yes, there could be multiple errors! ApolloServer provides error codes that will help to narrow down what caused the issues.

In our case, we only have one error with the code GRAPHQL_VALIDATION_FAILED, and it even tells us exactly which is invalid against our schema.

Within a server response, what keys can you expect to find in the JSON object?

To fix the error, we know we need to fix our , or ask our backend team to iterate on the schema and perhaps add the new .

Other errors can be particularly helpful when handled properly on the frontend, to inform the user on the nature of what went wrong, such as an invalid user input.

Finally, note that sometimes when a returns an error, it can still return some of the data you requested. We'll cover working with partial results like this in a future course.

When you query a field that is not in the schema, what error code will the server send?

Share your questions and comments about this lesson

Your feedback helps us improve! If you're stuck or confused, let us know and we'll help you out. All comments are public and must follow the Apollo Code of Conduct. Note that comments that have been resolved or addressed may be removed.

You'll need a GitHub account to post below. Don't have one? Post in our Odyssey forum instead.