-
-
Save sapandiwakar/fd1642a484826f2e02208d02c014fb55 to your computer and use it in GitHub Desktop.
Helper Methods to translate Ecto.Changeset errors to map or list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyAppWeb.Schema.Helpers do | |
def translate_changeset_errors(changeset) do | |
changeset | |
|> changeset_errors_to_map() | |
|> Enum.map(fn {key, errors} -> "#{key}: #{Enum.join(errors, ", ")}" end) | |
end | |
defp changeset_errors_to_map(nil), do: %{} | |
defp changeset_errors_to_map(changeset) do | |
Ecto.Changeset.traverse_errors(changeset, fn {msg, opts} -> | |
Enum.reduce(opts, msg, fn {key, value}, acc -> | |
try do | |
String.replace(acc, "%{#{key}}", to_string(value)) | |
rescue | |
Protocol.UndefinedError -> acc | |
end | |
end) | |
end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment