不要誤用 with
source link: https://dannypsnl.github.io/blog/2021/07/17/cs/elixir-with/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
身為一個多條件過濾器,許多人會像下面那樣誤用它。 然而正確的寫法應該是下面這樣。 其中的關鍵就在 會安心的吞掉錯誤,我們沒辦法判斷沒有拿到 究竟是因為沒有 或是 沒有通過驗證。第二種寫法就避開了這個問題,如果 比對失敗也會留下顯眼的紀錄,並且自動從錯誤中恢復。
不要誤用 with
with
身為一個多條件過濾器,許多人會像下面那樣誤用它。
with ["Bearer" <> token] <- get_req_header(conn, "authorization"),
{:ok, data} <- Authenicate.verify(token) do
%{current_user: get_user(data)}
else
%{}
end
然而正確的寫法應該是下面這樣。
with ["Bearer" <> token] <- get_req_header(conn, "authorization") do
{:ok, data} = Authenicate.verify(token)
%{current_user: get_user(data)}
else
%{}
end
其中的關鍵就在 with
會安心的吞掉錯誤,我們沒辦法判斷沒有拿到 current_user
究竟是因為沒有 token
或是 token
沒有通過驗證。第二種寫法就避開了這個問題,如果 {:ok, data}
比對失敗也會留下顯眼的紀錄,並且自動從錯誤中恢復。
author: Lîm Tsú-thuàn/林子篆/Danny
category:cs
tag:elixir
Similar Articles
All works in this site is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK