Correct way to handle 404 on phoenix liveview

Previously in a non-LV iteration, I would redirect the conn in a plug, populating the conn’s assigns with database objects (if found), otherwise render to the conn the error view’s ‘404.html’.

Since the lookup functionality is moved to mount, I’ve moved the plug code into a generic “populate_socket” function. I would like to make the redirect as generic as possible, hopefully just using the default phoenix error view.

I’ve thought of a couple of different ways to accomplish this, but I wanted to know how other folks are doing it.

I just raise an exception in mount/3 and let the configured :render_errors handle it.

def mount(%{"id" => id}, session, socket) do
  foo = Repo.get!(Foo, id)
  ...
end

Throwing Ecto.NoResultsError will return 404 correctly and use the default Phoenix ErrorView. No redirects necessary.

1 Like