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: errors
.
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 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.
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.
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.