From 2634ff76737568e1278fa9bfd0e2daf46e562b1f Mon Sep 17 00:00:00 2001 From: ruslandoga Date: Tue, 3 Sep 2024 18:35:07 +0700 Subject: [PATCH] Fix HTML-in-JSON in ErrorView (#4500) * fix html-in-json errors * add tests --------- Co-authored-by: hq1 --- lib/plausible_web/views/error_view.ex | 20 ++++++++++++++++++++ test/plausible_web/views/error_view_test.exs | 8 ++++++++ 2 files changed, 28 insertions(+) diff --git a/lib/plausible_web/views/error_view.ex b/lib/plausible_web/views/error_view.ex index 2e642e7e1..5d779c176 100644 --- a/lib/plausible_web/views/error_view.ex +++ b/lib/plausible_web/views/error_view.ex @@ -52,6 +52,14 @@ defmodule PlausibleWeb.ErrorView do end 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 |> Map.put_new(:message, Phoenix.Controller.status_message_from_template(template)) @@ -59,4 +67,16 @@ defmodule PlausibleWeb.ErrorView do render("generic_error.html", assigns) 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 diff --git a/test/plausible_web/views/error_view_test.exs b/test/plausible_web/views/error_view_test.exs index a7d5554cc..dd704dd85 100644 --- a/test/plausible_web/views/error_view_test.exs +++ b/test/plausible_web/views/error_view_test.exs @@ -13,4 +13,12 @@ defmodule PlausibleWeb.ErrorViewTest do refute error_html =~ "data-domain=" 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