Skip to main content

Handling GraphQL Errors with Status Code

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:

Handling GraphQL Errors with Status Code

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:

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!

Handling GraphQL Errors with Status Code
Handling GraphQL Errors with Status Code
Handling GraphQL Errors with Status Code
Handling GraphQL Errors with Status Code

Let’s see the final error output after implementation:

Handling GraphQL Errors with Status Code

Here we see the error has the properties message and statusCode also we can add extra values to the error message in resolver.

Conclusion

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

We'd love to talk about your business objectives

Written by