模式匹配HTTpoison响应Elixir

时间:2016-10-24 11:26:51

标签: elixir httpoison

我们是否有任何方式可以匹配httpoison的错误响应?我这样做了

case HTTPoison.get!(url, [], []) do
  %HTTPoison.Error{reason: reason} ->
    IO.inspect "Media: #{reason}!"
    :timer.sleep(:timer.seconds(3))
    do_loop(starting, ending, interval, camera_exid)
  response ->
    upload(response.status_code, response.body, starting, camera_exid)
    do_loop(starting + interval, ending, interval, camera_exid)
end

但它没有抓住timeout并且给我错误

** (HTTPoison.Error) :timeout
    (httpoison) lib/httpoison.ex:66: HTTPoison.request!/5
    (extractor) lib/snapshot/snap_extractor.ex:67: Extractor.SnapExtractor.do_loop/4
       (elixir) lib/enum.ex:651: Enum."-each/2-lists^foreach/1-0-"/2
       (elixir) lib/enum.ex:651: Enum.each/2

我认为我的做法是错误的..有什么建议吗?

1 个答案:

答案 0 :(得分:4)

HTTPoison.get!raise出现异常,而不会返回异常,因此您需要使用try ... rescue ...

try do
  response = HTTPoison.get!(url, [], [])
  upload(response.status_code, response.body, starting, camera_exid)
  do_loop(starting + interval, ending, interval, camera_exid)
rescue
  %HTTPoison.Error{reason: reason} ->
    IO.inspect "Media: #{reason}!"
    :timer.sleep(:timer.seconds(3))
    do_loop(starting, ending, interval, camera_exid)
end

然而,这不是一个好的代码,因为HTTPoison还有get,它返回{:ok, response}{:error, error},您可以按如下方式使用:

case HTTPoison.get(url, [], []) do
  {:ok, response} ->
    upload(response.status_code, response.body, starting, camera_exid)
    do_loop(starting + interval, ending, interval, camera_exid)
  {:error, %HTTPoison.Error{reason: reason}} ->
    IO.inspect "Media: #{reason}!"
    :timer.sleep(:timer.seconds(3))
    do_loop(starting, ending, interval, camera_exid)
end