elixirphoenix-frameworkplug

What's the correct way to respond to error page in a POST action without redirect in Phoenix?


I think it's a basic situation. I have a POST action, and I want to respond a 403 status and show the error page.

def signup(conn, params) do
  ...
  conn
  |> Plug.Conn.send_resp(:forbidden, "Forbidden")
  |> Plug.Conn.halt()
end

However, it will return the 403 but not render the error page. Instead, it throw Failed to load resource: the server responded with a status of 403 () in browser and download a weird signup.dms file.

I have an designed 403.html.eex, does anyone know how to show it correctly?


Solution

  • You need to render your template before you halt. It could look something like this:

    conn
    |> put_status(:forbidden)
    |> put_view(MyApp.ErrorView)
    |> render("403.html")
    |> halt()
    

    In this case you would need to create MyApp.ErrorView and create 403.html.eex in templates/error.