diff --git a/lib/trento_web/views/error_view.ex b/lib/trento_web/views/error_view.ex index 3f183477db..8763ec25ae 100644 --- a/lib/trento_web/views/error_view.ex +++ b/lib/trento_web/views/error_view.ex @@ -49,7 +49,11 @@ defmodule TrentoWeb.ErrorView do error = Ecto.Changeset.traverse_errors( changeset, - fn {message, _} -> message end + fn {message, opts} -> + Regex.replace(~r"%{(\w+)}", message, fn _, key -> + opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string() + end) + end ) %{ diff --git a/test/support/structs/test_data_with_validation.ex b/test/support/structs/test_data_with_validation.ex new file mode 100644 index 0000000000..1f6f88e689 --- /dev/null +++ b/test/support/structs/test_data_with_validation.ex @@ -0,0 +1,17 @@ +defmodule TestDataWithValidation do + @moduledoc false + + @required_fields :all + + use Trento.Support.Type + + deftype do + field :password, :string + end + + def changeset(changeset, attrs) do + changeset + |> cast(attrs, [:password]) + |> validate_length(:password, min: 8) + end +end diff --git a/test/trento_web/views/error_view_test.exs b/test/trento_web/views/error_view_test.exs index eb3225ecad..eb70c65384 100644 --- a/test/trento_web/views/error_view_test.exs +++ b/test/trento_web/views/error_view_test.exs @@ -111,6 +111,21 @@ defmodule TrentoWeb.ErrorViewTest do } == render(TrentoWeb.ErrorView, "422.json", changeset: changeset) end + test "should render a 422 error (changeset) with interpolated values" do + changeset = + TestDataWithValidation.changeset(%TestDataWithValidation{}, %{password: "short"}) + + assert %{ + errors: [ + %{ + detail: "should be at least 8 character(s)", + source: %{pointer: "/password"}, + title: "Invalid value" + } + ] + } == render(TrentoWeb.ErrorView, "422.json", changeset: changeset) + end + test "should render a 500 error" do assert %{ errors: [