moving err route handling to separate controller with proper layout plugs

This commit is contained in:
Adam Piontek 2021-04-07 13:22:10 -04:00
parent 0d6c95e301
commit 0bb011b59d
3 changed files with 72 additions and 27 deletions

View file

@ -0,0 +1,68 @@
defmodule Home73kWeb.ErrController do
use Home73kWeb, :controller
plug :put_layout, false
plug :put_root_layout, false
@valid_codes [
400,
401,
402,
403,
404,
405,
406,
407,
408,
409,
410,
411,
412,
413,
414,
415,
416,
417,
418,
421,
422,
423,
424,
425,
426,
428,
429,
431,
451,
500,
501,
502,
503,
504,
505,
506,
507,
508,
510,
511
]
def err(conn, params) do
code = Map.get(params, "code", "404") |> err_code_as_int()
code = (code in @valid_codes && code) || 404
conn
|> put_status(code)
|> put_layout(false)
|> put_root_layout(false)
|> put_view(Home73kWeb.ErrorView)
|> render("#{code}.html")
end
defp err_code_as_int(code) do
try do
String.to_integer(code)
rescue
_ -> 404
end
end
end

View file

@ -16,29 +16,4 @@ defmodule Home73kWeb.HomeController do
def folio(conn, _params) do def folio(conn, _params) do
render(conn, "folio.html", page_title: "Folio") render(conn, "folio.html", page_title: "Folio")
end end
@valid_codes [400..418, 421..426, 428..429, 500..508]
|> Enum.map(&Enum.to_list/1)
|> Enum.concat()
|> Enum.concat([431, 451, 510, 511])
def err(conn, params) do
code = Map.get(params, "code", "404") |> err_code_as_int()
code = code in @valid_codes && code || 404
conn
|> put_status(code)
|> put_layout(false)
|> put_root_layout(false)
|> put_view(Home73kWeb.ErrorView)
|> render("#{code}.html")
end
defp err_code_as_int(code) do
try do
String.to_integer(code)
rescue
_ -> 404
end
end
end end

View file

@ -24,8 +24,6 @@ defmodule Home73kWeb.Router do
get "/about", HomeController, :about get "/about", HomeController, :about
get "/resume", HomeController, :resume get "/resume", HomeController, :resume
get "/folio", HomeController, :folio get "/folio", HomeController, :folio
get "/err", HomeController, :err
get "/err/:code", HomeController, :err
# Blog # Blog
live "/blog", BlogLive, :index live "/blog", BlogLive, :index
@ -35,6 +33,10 @@ defmodule Home73kWeb.Router do
# Feeds # Feeds
get "/feed", FeedController, :rss get "/feed", FeedController, :rss
# Error fun/testing
get "/err", ErrController, :err
get "/err/:code", ErrController, :err
end end
# Other scopes may use custom stacks. # Other scopes may use custom stacks.