Get the information about login users in ErrorView

Hi!

I want to customize 404 and 500 pages for authorized and not authorized users. In the first case, I want to add nav bar with the user avatar and navigations, in the second case, it will the page without navigations and user info. Assigns in ErrorView do not contain any information about the user (no id, session data, token, etc.). Is there a way to get current user info for designing error pages?

Below, I put my current view.
Thanks

defmodule MyAppWeb.ErrorView do
  use MyAppWeb, :view

  def render("404.html", assigns) do
    render("404_page.html", assigns)
  end

  def render("500.html", _assigns) do
    render("500_page.html", %{})
  end

  def template_not_found(template, _assigns) do
    Phoenix.Controller.status_message_from_template(template)
  end
end

If you are implementing a web application with user system, you should have something like this in your router:

pipeline :browser do
  # ...
  plug :fetch_current_user
  # ...
end

:fetch_current_user assigns current user into conn.assigns.current_user.

Then, conn.assigns can be visited via assigns in your MyAppWeb.ErrorView.render/2.

Checkout hex package - phx_gen_auth for more details.

That’s by design. What if the error view failed because you could not fetch the session? Or because the user_id was invalid?

Therefore, in order to avoid going into a scenario where you can’t even render the error view, it is best recommended for the error views to be as devoid of logic as possible.