Elixir "case clause error" 模式匹配 HTTPoison 响应
Elixir "case clause error" while pattern matching HTTPoison response
我正在使用 Httpoison 执行获取请求,我想使用 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) no case clause matching:
当我收到正文和状态代码为 200 的响应时,为什么会出现 "no clause" 错误?
问题是 get
之后的 !
HTTPoison.get!(@api_url)
将 return %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
或
def current() do
%HTTPoison.Response{body: body, status_code: 200}} = HTTPoison.get!(@api_url)
IO.puts body
end
我正在使用 Httpoison 执行获取请求,我想使用 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) no case clause matching:
当我收到正文和状态代码为 200 的响应时,为什么会出现 "no clause" 错误?
问题是 get
!
HTTPoison.get!(@api_url)
将 return %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
或
def current() do
%HTTPoison.Response{body: body, status_code: 200}} = HTTPoison.get!(@api_url)
IO.puts body
end