Fix HTML-in-JSON in ErrorView (#4500)

* fix html-in-json errors

* add tests

---------

Co-authored-by: hq1 <hq@mtod.org>
This commit is contained in:
ruslandoga 2024-09-03 18:35:07 +07:00 committed by GitHub
parent 53d94b5b1b
commit 2634ff7673
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 28 additions and 0 deletions

View File

@ -52,6 +52,14 @@ defmodule PlausibleWeb.ErrorView do
end end
def template_not_found(template, assigns) do def template_not_found(template, assigns) do
if String.ends_with?(template, ".json") do
fallback_json_error(template, assigns)
else
fallback_html_error(template, assigns)
end
end
defp fallback_html_error(template, assigns) do
assigns = assigns =
assigns assigns
|> Map.put_new(:message, Phoenix.Controller.status_message_from_template(template)) |> Map.put_new(:message, Phoenix.Controller.status_message_from_template(template))
@ -59,4 +67,16 @@ defmodule PlausibleWeb.ErrorView do
render("generic_error.html", assigns) render("generic_error.html", assigns)
end end
defp fallback_json_error(template, _assigns) do
status =
String.split(template, ".")
|> hd()
|> String.to_integer()
message = Plug.Conn.Status.reason_phrase(status)
%{status: status, message: message}
rescue
_ -> %{status: 500, message: "Server error"}
end
end end

View File

@ -13,4 +13,12 @@ defmodule PlausibleWeb.ErrorViewTest do
refute error_html =~ "data-domain=" refute error_html =~ "data-domain="
end end
test "renders json errors" do
assert Phoenix.View.render_to_string(PlausibleWeb.ErrorView, "500.json", %{}) ==
~s[{"message":"Server error","status":500}]
assert Phoenix.View.render_to_string(PlausibleWeb.ErrorView, "406.json", %{}) ==
~s[{"message":"Not Acceptable","status":406}]
end
end end