Render Phoenix Error View inside Plug
Phoenix Error view ( https://hexdocs.pm/phoenix/views.html#error-pages ) is an interesting tool to organize your applications custom errors showing a friendly error message.
However, render moment is after controllers execution. When you create a Plug (https://hexdocs.pm/phoenix/plug.html#content) , it is placed on top of Endpoint level ( endpoint.ex
), before router moment, which makes impossible to use redirect strategies to show error pages because it raises a stack level too deep
exception
So, inside Plug level, you have to render error views manually. Let's take a look on below code
This plug is responsible to authorize user access. Just it. When user can not access, a friendly error page is rendered based on http status.
MyAppWeb.ErrorView
module belongs to folder my_app_web/views/error_view.ex
. The file content looks like that:
You have to notice you don't need to create def 401 do
method. Phoenix automatically find error templates by name inside the folder my_app_web/templates/error
. In our use case, Phoenix will find my_app_web/templates/error/401.html.eex
Let take a look too 401.html.eex
file content:
It is just a HTML file :D
I hope this article be helpful to you. If you have any questions, leave a comment bellow ;)