0

I am trying to return an invalid changeset.

When doing

conn
|> put_status(422)
|> put_view(Elemental.Auth.ErrorView)
|> render("422.json-api", %{data: changeset})

OR

conn
|> put_status(422)
|> put_view(Elemental.Auth.ErrorView)
|> render(:errors, data: changeset)

using JaSerializer I am getting

(Poison.EncodeError) unable to encode value: {"has already been taken", []}

This was unexpected. It was working earlier. I have {:poison, "~> 2.0"},

UPDATE

>> d
%{errors: [shortcode: {"has invalid format", [validation: :format]}]}
iex(11)> Map.replace(d, :errors, [shortcode: Tuple.to_list(shortcode)]) |> Poison.encode
{:error,
 {:invalid, {:shortcode, ["has invalid format", [validation: :format]]}}}
user2290820
  • 2,709
  • 5
  • 34
  • 62

1 Answers1

1

Poison never knew how to encode the tuple. You can easily convert tuple to the list:

a = {"has already been taken", []}

a 
|> Tuple.to_list() # ["has already been taken", []]
|> Poison.encode!() # "[\"has already been taken\",[]]"

Or simply get first_entry from the tuple using pattern matching:

{message, _list} = {"has already been taken", []}

Edit:

Your code is crashing when trying to display explicitly the changeset. The best solution to avoid that is to create specific view, that will return JSON where you can prepare how you want to display the errors eg.

def render("422.json-api", %{data: data}) do
  # data is actually changeset, which you are passing here
  errors = Enum.map(data.errors, fn {field, message} -> 
    %{field: "#{field} has error: #{message}"
  end)

  %{errors: errors}
end
PatNowak
  • 5,721
  • 1
  • 25
  • 31
  • see updates, what do you mean >but it turns out you displaying propably only the first one ? – user2290820 Oct 31 '17 at 10:50
  • Ok I edited my answer. The easiest way to avoid explicitly using `Poison.encode!` is to create View that will do that implicitly for you and you have full control what you want to render. – PatNowak Oct 31 '17 at 12:00
  • because it was a tuple, i just extracted and matched the clause and yielded the output. thanks – user2290820 Nov 01 '17 at 05:16