Skip to content

Instantly share code, notes, and snippets.

@sapandiwakar
Created May 19, 2023 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sapandiwakar/fd1642a484826f2e02208d02c014fb55 to your computer and use it in GitHub Desktop.
Save sapandiwakar/fd1642a484826f2e02208d02c014fb55 to your computer and use it in GitHub Desktop.
Helper Methods to translate Ecto.Changeset errors to map or list
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