Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Interpolate validation errors in error view #2616

Merged
merged 1 commit into from
May 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading