我正在使用Httpoison来执行get请求,我希望使用case语句对响应进行模式匹配。这是代码:
def current() do
case HTTPoison.get!(@api_url) do
{:ok, %HTTPoison.Response{body: body, status_code: 200}} ->
IO.puts body
{:error, %HTTPoison.Error{reason: reason}} ->
IO.inspect reason
end
end
当状态代码为200时,打印正文。 出现错误时,请检查原因。
我从服务器得到响应,如此,
%HTTPoison.Response{body: "{\"USD\":10067.08}", headers: <<removed for readability>>, status_code: 200}
错误,(CaseClauseError)没有案例子句匹配:
当我收到身体和状态代码为200的回复时,为什么会出现“无子句”错误?
答案 0 :(得分:1)
问题是!
get
HTTPoison.get!(@api_url)
将返回%HTTPoison.Response{body: body, ...}
或提出异常。
如果您需要{:ok, %HTTPoison.Response{body: body, ...}
,请改用HTTPoison.get(@api_url)
(不使用!
)。
要么:
def current() do
case HTTPoison.get(@api_url) do
{:ok, %HTTPoison.Response{body: body, status_code: 200}} ->
IO.puts body
{:error, %HTTPoison.Error{reason: reason}} ->
IO.inspect reason
end
end
OR
def current() do
%HTTPoison.Response{body: body, status_code: 200}} = HTTPoison.get!(@api_url)
IO.puts body
end