Skip to content

Commit

Permalink
Interpolate validation errors in error view (#2616)
Browse files Browse the repository at this point in the history
  • Loading branch information
arbulu89 committed May 13, 2024
1 parent b089003 commit 004cfea
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/trento_web/views/error_view.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

%{
Expand Down
17 changes: 17 additions & 0 deletions test/support/structs/test_data_with_validation.ex
Original file line number Diff line number Diff line change
@@ -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
15 changes: 15 additions & 0 deletions test/trento_web/views/error_view_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand Down

0 comments on commit 004cfea

Please sign in to comment.