Error Handling

Learn how to implement error handling in GraphQL resolvers.

We’ve already implemented a good portion of our backend and added a number of queries and mutations to our API, but we still don’t have any error handling code! What happens if a user sends a request with an invalid ID or malformed input? GraphQL schema checks alone are not enough to protect our application from this.

In this lesson, we’ll learn how to add error handling to our GraphQL API and how to customize error responses. We’ll implement error handling for just a few resolvers, but it should be noted that error handling should be a more expansive undertaking.

Returning errors from a GraphQL resolver

Returning an error from a GraphQL API is pretty straightforward. All we need to do is throw one of the exceptions defined by Apollo Server into one of our resolvers.

Let’s see how we can do it in our API and implement error handling for the productsByAuthor query. This query expects a username as a parameter and uses it to fetch products authored by a user with that name. It’s a good idea to check and see if a user with this name exists and if our API will return an error if they don’t.

We need to import the UserInputError exception type, which is used if the input passed to a resolver is invalid, and throw an instance of this exception if our input validation fails.

Get hands-on with 1200+ tech skills courses.