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.
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.
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 the server will send back its response.
In the response, we'll see a new key:
tracksForHomewith 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 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 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 backend 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?