Athunnea

Athunnea

How do you provide custom error message for Ecto's cast errors?

If you provide a string to an :integer field you get
errors: [count: {"is invalid", [type: :integer, validation: :cast]}]
in a changeset, which is not helpful for a user. Unfortunately Ecto.Schema.field/3 doesn’t accept custom error messages (as of v3.9 at least).

I want to return something like “should be a number” to a user instead of “is invalid”.

One solution could be a create a custom integer type, which can return a custom error message. Another way could be processing this in web layer in some kind of humanize_error function, replacing default “is invalid” with “should be a number”.

For now I’ve settled with custom ecto types, but as their number started to grow, I want to re-evaluate my approach. So I wonder how do others solve similar issues? I would appreciate your thoughts.

PS. What I like about custom types, is that I can also use them to clean up values before casting them. I can trim strings, remove double spaces, drop “.0” and “,0” from integers.

Most Liked

D4no0

D4no0

Have you tried using gettext for this? You should have some examples in a generated phoenix project.

LostKobrakai

LostKobrakai

The metadata in the error would allow you to do the transformation you mention to the error in Ecto.Changeset.traverse_errors (which is likely already called somewhere in your codebase). You can ignore the existing error string and match on metadata[:validation] + metadata[:type].

Last Post!

endymion

endymion

I made a post discussing how we solved this issue.

It boils down to creating a function

  @doc """
  Overwrites the error message for `Ecto.Changeset.cast/4` from `"is invalid"` to the
  custom supplied error message.
  """
  def custom_cast_error_message(changeset, field, message) do
    errors = Enum.map(changeset.errors, fn {error_field, {_msg, opts}} = error ->
      if field == error_field && opts[:validation] == :cast do
        {field, {message, opts}}
      else
        error
      end
    end)

    %{changeset | errors: errors}
  end

and calling it like

message = "This is our custom error message for cast/4"

Ecto.Changeset.cast(answer, params, [:value])
|> Aw.Changeset.custom_cast_error_message(:value, message)

Where Next?

Popular in Questions Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

We're in Beta

About us Mission Statement