Working with error handling for UUID and GraphQL/Absinthe

The purpose of what I’m doing is I’m creating an invitation key in order to invite people to the application. It will have a schema of

  @primary_key {:id, :binary_id, autogenerate: true}
  @derive {Phoenix.Param, key: :id}
  schema "referrals" do
    field(:is_valid, :boolean, default: true)


When someone types in a valid UUID, there aren’t any problems. But the problem occurs when I try to add either a custom logic for bringing up accurate errors. Anyone can provide advice on what approach you’ve taken?

  def get_referral(_, %{invitation_code: code}, _) do
    case Ecto.UUID.cast(code) do
      {:ok, code} ->
        {:ok, Accounts.get_referral!(code)}

      {:error} ->
        {:error, "This doesn't look right"}

I thought checking if it’s a valid UUID would be the best approach but every time I try to send an error back, I’m always seeing something like this is the error Error: Network error: Unexpected token < in JSON at position 0 or not really an error message that I can use to show in the frontend.

It seems like on the frontend if I did err.graphQLErrors[0].message, I’ll be able to parse the error the right way :thinking:

Your client can’t parse entire response as a json, so I think, you have some exception and phoenix displays it as html.
Actually, you have invalid pattern matching. Ecto.UUID.cast/1 returns :error, not {:error}.

1 Like

Your browser couldn’t parse the JSON because the content isn’t JSON. The content isn’t JSON because Absinthe crashed out instead of returning an error. Absinthe crashed out because it doesn’t recover from exceptions: if you want a GraphQL error, your resolvers need to return {:error, binary_reason} instead of crashing out. Finally, your resolver crashed out for the reason @fuelen pointed out.

1 Like

Thank you for replying and I apologize for being late. You were right in regards to both statement. Thank you for that explanation. I need to get a better hang on understanding what I’ll be getting as a return when something works and when something fails, in this case just a :error and not a tuple.

Thank you for replying to my question. It is exactly as you’ve mentioned. I made the assumption that since were using GraphQL and it’s based on JS, the response would be parsed to be acceptable to the frontend. This was a mistake on my part and another was not being able to fully understand what I would expect if it were to fail. With I finally have thanks to learning how to read the docs better and @fuelen. Thank you both for the help on this matter.

You’re welcome, @Yama!