Case Statements for Error Handling in Ecto Changesets

Hi all! Going through the Ecto docs and trying to understand something-

Makes sense to me for their suggestion to use a case statement like

case Friends.Repo.insert(changeset) do
  {:ok, person} ->
    # do something with person
  {:error, changeset} ->
    # do something with changeset
end

for the error handling- just not quite sure how that’s implemented with the an existing Schema changeset like-

def changeset(person, params \\ %{}) do
  person
  |> Ecto.Changeset.cast(params, [:first_name, :last_name, :age])
  |> Ecto.Changeset.validate_required([:first_name, :last_name])
end

How exactly is this case statement wrapped in def changeset?

Additionally, in this case statement: what am I doing with the first {:ok, person} tuple? I understand with the {:error, changeset} tuple I can return something like-

traverse_errors(changeset, fn {msg, opts} ->
  Enum.reduce(opts, msg, fn {key, value}, acc ->
    String.replace(acc, "%{#{key}}", to_string(value))
  end)
end)

Thanks for any help :slight_smile:

The Changeset.* functions accept a changeset as a first argument and return an updated changeset. That enables the piping you’re seeing. At any point in the pipe you can inspect whether the changeset now has errors and if you want to do something about it.

1 Like