diff --git a/lib/plausible_web/views/error_view.ex b/lib/plausible_web/views/error_view.ex index 2e642e7e15..5d779c1766 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 a7d5554cc9..dd704dd850 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