chadcf
Handling http errors from HTTPoison / Hackney
I’m attempting to gracefully handle failures from an api call and am struggling a bit with how to do this. Take for example the following:
case HTTPoison.get("https://url.com") do
{:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
...
{:error, %HTTPoison.Error{} = error} ->
...
end
Works great for one real world test case. What I’m struggling with is two things:
- Under what circumstances does HTTPoison return :error vs :ok? I can’t find this anywhere. I don’t know if it’s possible that it would ever return :ok with a status code of 500, or if it will always return :error on any status code > 400 or what… Do I need to match on both :error as well as :ok with a status code > 400 to catch failures?
- I cannot for the life of me figure out how to test this. We’re using Bypass in our tests, and I can have it return a
Plug.Conn.respwith a 500 status code but the actual response still comes back with an :ok and not :error. I cannot for the life of me figure out how to get Bypass to return an :error response.
Any help is greatly appreciated!
Most Liked
NobbZ
When the server sent a reply you’ll get an :ok tuple, if the request timed out, DNS couldn’t be resolved or otherwise a connection couldn’t be established, then you’ll see :error tuple returned, also if the reply sent by the server is not parsable as HTTP.
wojtekmach
I cannot for the life of me figure out how to get Bypass to return an :error response.
See the example from README where Bypass.down/1 can be used to take the TCP server down, you should get an {:error, _} response then. Your mocked response may also do Process.sleep(:infinity), that should trigger a timeout somewhere too.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









