Reputation: 151
1) How can I handle "server error" and "page not found" on the application level? Where should I put a handler which renders appropriate pages?
That is, if a user goes to "my_website.com/fdafdsafds" -- how can I render the page "error/my_custom_404_page.html" to him?
Or if somewhere in my app an error occurs such as "1 / 0", how can I catch it on the application level?
2) Inside a plug I have this:
def call(conn, opts) do
if !some_condition do
# ....
else
# how to render an html template?
Conn.send_resp(conn, 401, "access denied") |> Conn.halt()
end
end
How can I render my custom error html template from "error/my_html_template.html" and pass parameters to it?
Upvotes: 1
Views: 2000
Reputation: 121010
TL;DR You are to declare custom exceptions (with standard Elixir defexception
macro) and to implement Plug.Exception
protocol for them, like this:
defimpl Plug.Exception, for: Ecto.NoResultsError do
def status(_exception), do: 418
end
Then, once raised, it will be handled by this implementation.
There is a detailed description on how to do this in Phoenix documentation. I do not see any reason to copy the content from there, but I must admit the explanation is pretty straightforward.
Upvotes: 3
Reputation: 560
1) How can I handle "server error" and "page not found" on the application level? Where should I put a handler which renders appropriate pages?
I used following trick
scope "/", MyApp do
post "/*path", PageController, :invalid_path
put "/*path", PageController, :invalid_path
get "/*path", PageController, :invalid_path
end
And define custom error message in invalid_path method.
NOTE: Add these lines at end of the router file
Upvotes: -1