Here's an example error response from my GraphQL server:
{
"data":null,
"errors":[{
"message":"The tenant could not be found.",
"name":"TenantNotFoundError"
}]
}
I would like to implement some logic in the frontend according to the error name (TenantNotFoundError) and not its message, but urql provides this to work with, which doesn't contain the error name:
{
"name": "CombinedError",
"message": "[GraphQL] The tenant could not be found.",
"graphQLErrors": [
{
"message": "The tenant could not be found.",
"extensions": {}
}
],
"response": {}
}
Is there any way to accomplish this?
I'd like to be able to do something like:
const [res] = useQuery({ query });
if (res.error.name === "TenantNotFoundError") { ... }
Matching errors by message, instead of some identifier (error name or code) seems pretty brittle to me and doesn't work well with internationalization.
Thank you.
Since a lot of people will be using other keywords here as in name could be code,... We should maybe offer an exchange or option to transform errors.
I think that could solve the problem of having to handle x amount of keywords
The PR that has been linked properly adds the originalError to the unserialised GraphQLError, as it should鈥檝e been in the first place.
I just wanted to leave a small clarification here to avoid any confusion :)
In the GraphQL specification there鈥檚 a list of properties that are standardised to be sent as GraphQL errors, while raw strings as messages are allowed as well. The name property is not a part of this curiously.
The JS library deals with this spec by having the GraphQLError class that abstracts this, which our CombinedError exposes as an array property (hence a single name property doesn鈥檛 make sense, since we may be dealing with multiple error)
This means that you have the option to use extensions to encode your error code or identifier. But after the above PR is published you could also use error.graphQLErrors[i].originalError.name.
That being said, the most solid approach is to use explicit GraphQL errors on your backend which will be fully deserialised and to attach custom extensions to them. Hope that makes sense 馃憤
Amazing, thank you!
Most helpful comment
Since a lot of people will be using other keywords here as in
namecould becode,... We should maybe offer anexchangeoroptionto transform errors.I think that could solve the problem of having to handle x amount of keywords