Urql: how to retrieve the error name as provided by the graphql server?

Created on 15 Nov 2019  路  3Comments  路  Source: FormidableLabs/urql

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.

Most helpful comment

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

All 3 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fivethreeo picture fivethreeo  路  5Comments

wodnjs6512 picture wodnjs6512  路  3Comments

pix2D picture pix2D  路  4Comments

andyrichardson picture andyrichardson  路  4Comments

narinluangrath picture narinluangrath  路  3Comments