Reputation: 2598
Is there any way that we can pattern match the error response of httpoison
? I was doing this
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
But It didn't catch the timeout
and gave me error as
** (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
I think am doing it in wrong way.. Any suggestions?
Upvotes: 2
Views: 1044
Reputation: 222040
HTTPoison.get!
will raise
an exception, not return one, so you need to use 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
This is however not considered good code since HTTPoison also has get
which returns {:ok, response}
or {:error, error}
which you can use as follows:
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
Upvotes: 5