Is it possible to render a “fallback” component when an error doesn’t match one of the templates added to the error_html directory? The example given in Custom Error Pages — Phoenix v1.7.0 would just print the bare error string without rendering a component if a template is not found.
With Phoenix.View I could set up ErrorView like:
defmodule MyAppWeb.ErrorView do
use MyAppWeb, :view
def render("403.html", assigns) do
render(
"error.html",
Map.merge(
%{
title: "Access denied",
message: "Sorry, you do not have access to the requested page."
},
assigns
)
)
end
# another render() for 404.html etc...
# and a fallback if a specific error is not handled above
def template_not_found(template, assigns) do
render(
"error.html",
Map.merge(
%{
title: Phoenix.Controller.status_message_from_template(template),
message: "Sorry, we experienced an unexpected error."
},
assigns
)
)
end
end
With the above I can have the 1 pretty error template that can handle all the errors, and pass in assigns with the error title and message.
I can’t seem to make this work with ErrorHTML. I either seem to get stuck in an inifinte render loop, or no matching clause.
defmodule HelloWeb.ErrorHTML do
use HelloWeb, :html
embed_templates "error_html/*"
# render the fallback template
def render(template, assigns) do
status = assigns.status
message = Phoenix.Controller.status_message_from_template(template)
fallback(%{status: status, message: message})
end
end
Oh, brilliant, I had no idea you could call a functional component like that… I assumed you had to call it like a component (in a heex block), but that works great. Thank you!