Any application, from simple to complex, can have errors. It is important to handle these errors and report these errors back to your users for information.
The question is - How do we handle errors in GraphQL? How can we do it in a way that’s easy to understand?
Let’s start by running a simple GraphQL query:
Here we can see, we get an error, this error can be found in the errors array.
This is how errors can be found in a GraphQL response. But the error is not very clear and meaningful. Here are some problems with such error representations:
- All errors are treated the same
- It’s difficult to know where the error came from
- It’s tough for the user to understand what exactly the errors talk about
Let’s see how to handle errors with a status code
For this, you need to add customFormatErrorFn that will handle all the errors thrown from your queries and mutations. Let’s see the steps for creating our error response.
How to do it!
- Create a constants file with the error name and the error type: errorConstant.ts
- We will need a function that will search on errorType for the properties of the error, we can create a new file or set it in index.ts file
- When you resolve a query or mutation, and an error occurs, you might throw the error message with the constant that you define in errorConstant.ts file.
- And finally, we update index.js so we can return our custom error. We‘ll add customFormatErrorFn in graphqlExpress when initializing GraphQL within Express.
Let’s see the final error output after implementation:
Here we see the error has the properties message and statusCode also we can add extra values to the error message in resolver.
GraphQL does not describe errors in error handling. It’s up to you to decide what describes your errors.
Click here for the code link gqlErrorHandling