Catch All Route or Custom Error Handler for 404

I’d like to implement a catch all route, or at least an Error Handler that can redirect to a custom path that exists.

I tryed set up a plug but received an endpoint error message (when tryed route existed) or no route found.

What’s the best approach?

1 Like

Does this help from the guides?

https://hexdocs.pm/phoenix/views.html#the-errorview

The ErrorView

Phoenix has a view called the ErrorView which lives in lib/hello_web/views/error_view.ex. The purpose of the ErrorView is to handle two of the most common errors - 404 not found and 500 internal error - in a general way, from one centralized location.

(Also please use Markdown to format your posts)

2 Likes

Thanks.

I got it working for “/” or “/.” (request.html)

router.ex

  scope "/", TrainerWeb do
    pipe_through :browser
    get "/", PageController, :index
    get "/:page", PageController, :index
  end

error_view.ex

  alias TrainerWeb.Router.Helpers
  alias Phoenix.Controller

  defp customredirect(conn) do
    action = :index
    route = "page_path"
    module = Module.concat(Helpers, route |> String.capitalize |> String.to_atom)
    params = conn.params
    conn
    |> Controller.redirect(to: apply(module, :func, [conn, action, params]))
  end

  def render("404.html", assigns) do
    assigns.conn
    |> customredirect()
  end
3 Likes