9. Errors! When queries go sideways

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 south. In our query journey, when the server is validating the query AST against the schema, it could run into invalid fields 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 query for the numberOfViews field, because we want to add that piece of data to our tracks card on the homepage. We know that it exists in our data source because we even saw the /tracks endpoint return it!

That is true, but the numberOfViews field is not a part of our GraphQL schema. And if we try to add it to the query, 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 query, and it will start its journey. But that journey will be cut short at the server validation step, at which point it will be sent back.

In the response that's sent back, we'll see that the data we receive is null, as well as a new key: errors.

Code Challenge!

On Apollo Studio Explorer, replace all selected fields inside tracksForHome to just 'numberOfViews'. Copy-paste the whole response below.

errors is an array containing each error that occurred as the server tried to execute the query. So yes, there could be multiple! 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 field 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 query, or ask our back-end team to iterate on the schema and perhaps add the new field.

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 query 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?