Using enums for error codes
It is important to be mindful of the granularity of errors. While it may be tempting to return a single generic error for all scenarios, it is better to provide more specific error messages for individual scenarios. This allows clients to understand the root cause of the error and take appropriate actions. By being specific, we can guide developers toward the right solutions and save valuable debugging time.
By specifying an enum with error variants, we can return errors as a valid GraphQL response. Then the schema consumer – depending on which ErrorVariant
is returned – can handle it in their own way.
In this short example, we will specify an enum to be used as an error descriptor. Here is the schema:
type Post{ title: String content: String } enum ErrorVariant{ NOT_FOUND FORBIDDEN } type PostResponseVariant{ posts: [Post!] errors: [ErrorVariant!] } type Query...