Treating errors as data
Another possible method to describe errors in GraphQL is to treat them as data. Unlike traditional REST APIs, where errors are often returned as HTTP status codes, GraphQL encourages us to model errors using GraphQL types. This approach enables clients to understand and describe errors in a more structured and predictable manner. This way, schema consumers can receive fully described expected error descriptions and simply display them to the end user.
Let’s take a look at an example. In the following schema, we created a dedicated PostError
type to keep the structure of the error response inside our GraphQL schema:
type Post{ title: String content: String } enum ErrorVariant{ NOT_FOUND FORBIDDEN } type PostError{ message: String! variant: ErrorVariant } type PostDescribedResponse{ posts: [Post!] errors: [PostError!] } type Query{ describedErrors...