因此,我正在嘗試構建一個具有一些錯誤處理的插件,並且如果用戶未通過身份驗證發送響應。這裏是我的代碼:發送send_resp發送數據的問題
def unauthorized(conn) do
respond(conn, response_type(conn), 401, "Unauthorized")
end
defp response_type(conn) do
accept = accept_header(conn)
if Regex.match?(~r/json/, accept) do
:json
else
:html
end
end
defp accept_header(conn) do
value = conn
|> get_req_header("accept")
|> List.first
value || ""
end
defp respond(conn, :json, status, msg) do
try do
conn
|> put_resp_content_type("application/json")
|> send_resp(status, Poison.encode!(%{errors: msg}))
|> IO.inspect
|> halt
rescue ArgumentError ->
conn
|> put_resp_content_type("application/json")
|> send_resp(status, Poison.encode!(%{errors: [msg]}))
|> halt
end
end
所以它幾乎工作,該檢查是看到一個
狀態:發送狀態:401
上發送的,但從來沒有送我錯誤信息。
我想第二個問題是,我真正想做的是將許多這些模板保存在error_view.ex文件中並使用Phoenix的渲染。
看到宏選擇命名約定使用有沒有辦法讓我在另一個模塊中強制渲染某個視圖?
我對Elixir相當陌生,所以非常感謝您的幫助!
編輯:
所以我發現put_view,但似乎不工作,當我有比200
以外的任何錯誤代碼,如果我做任何錯誤代碼它似乎沒有發回消息,但只是專門爲這個插件。如果我在我的控制器的任何其他地方對它執行put_status,它工作得很好,但不在這裏。
這是新代碼:
defp respond(conn, :json, status, msg) do
try do
conn
|> put_resp_content_type("application/json")
#|> send_resp(status, Poison.encode!(%{errors: msg}))
|> put_status(status)
|> put_view(ChatApp.Web.UsersView)
|> render("error_user_creation.json", string: msg)
|> IO.inspect
|> halt
rescue ArgumentError ->
conn
|> put_resp_content_type("application/json")
|> send_resp(status, Poison.encode!(%{errors: [msg]}))
|> halt
end
end
然而正在發送,我只要它是200狀態發送了機身右側,如果是別的就會失敗。
編輯,編輯:
我的代碼將運行的200狀態碼完全合理的,但其他地把東西的時候,它打破:
它被稱爲是這樣的:
case Accounts.check_token(List.first(token)) do
{:ok, user} ->
conn
|>GeneralUtils.put_private(:user, user)
|> AuthResponses.unauthorized
:error ->
conn
|> GeneralUtils.put_private(:error, {:error, "You do not have permissions"})
end
另外我知道這AuthResponses.unauthorized應該是錯誤的,我只是測試目前,這很容易。
有一個'Phoenix.Controller.get_format/1'函數來獲取請求格式。 (接受插件會把你的格式爲conn) – sysashi
酷!我用get_format函數更新了我的response_type。謝謝! –