Absinthe: Protocol Enumerable not implemented for #Ecto.Changeset

Hello everyone, I am new to elixir and phoenix but I’ve been already fallen in love with them, but unfortunately I got stuck in a problem when I was developing a validation for my first API with Absinthe. When I just list all accounts, or create a new account without failing on any validation everything works fine, but
Whenever I tried to validate the current_balance > 0, and it is equals or lower than 0 in a custom validation on the changeset I get the error:

Request: POST /api/graphiql

** (exit) an exception was raised:
    ** (Protocol.UndefinedError) protocol Enumerable not implemented for #Ecto.Changeset

the code of the account schema I’ve trying to implement its followed above:

defmodule GraphBanking.Accounts.Account do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "accounts" do
    field(:current_balance, :float)
    timestamps()
  end

  @doc false
  def changeset(account, attrs) do
    account
    |> cast(attrs, [:current_balance])
    |> validate_required([:current_balance])
    |> validate_balance()
  end

  defp validate_balance(changeset) do
    currentBalance = get_change(changeset, :current_balance)
    IO.inspect(currentBalance)
    if(currentBalance <= 0) do
      changeset
      |> add_error(:current_balance, "It must be higher than 0")
    else
      changeset
    end
  end
end

Any help would be more than appreciated

Hi @andersonRocha091!

There’s a wiki page on error handling in absinthe here: https://github.com/absinthe-graphql/absinthe/blob/master/guides/errors.md

For changesets, it points to this library: https://github.com/mirego/absinthe_error_payload

Hope that helps!

2 Likes

Hi @blatyo , firstly would like to thank you for your help, but unfortunately I dont think it would be the solution because absinthe_error_payload extention requires an old version of absinthe_ecto, phoenix_ecto, etc.

I got the following errors when I tried to install absinthe_error_payload
Failed to use “ecto” (version 2.2.12) because

  • absinthe_ecto (version 0.1.3) requires >= 0.0.0*
  • absinthe_error_payload (version 1.0.1) requires ~> 3.1*
  • phoenix_ecto (version 3.6.0) requires ~> 2.2*
  • mix.lock specifies 2.2.12*

Seems like it actually wants a newer version of ecto.

But it can’t upgrade because you’re using an older version of phoenix_ecto.

You can use mix hex.outdated --all to list all the packages that are outdated in your project.

2 Likes

Hey @blayto I got it working! I found in absithe wiki an description where they teach how to build an middleware to deal wit ecto errors properly, in order to get the message in a format accepted by absinthe. I followed their tutorial and worked like a charm. Thanks for you help.

1 Like

Mind linking to what helped you?

1 Like