I am relying on Ecto to return an error when an insert fails a database level constraint.
Is it possible to run different code depending on the error type returned by Ecto?
case Repo.insert(changeset) do
{:ok, _} ->
IO.puts("inserted")
{:error, message} when is_certain_ecto_error ->
IO.puts("database constraint error")
{:error, message} ->
IO.puts("everything else error")
end
Like Justin said, you will get {:error, changeset}
, the changeset would have the errors
keyword list, where you can pattern match on.
case Repo.insert(changeset) do
{:ok, _} ->
IO.puts("inserted")
{:error, %{ errors: errors }} ->
Enum.map(errors, &handle_error(&1))
end
defp handle_error({:user_name, {message, _}}) do
"User name error:" <> message
end
defp handle_error({_some_key, _error_tuple}), do: "some error"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With