0

I'm using Httpoison to perform a get request and I want to pattern match the response using a case statement. Here is the code:

  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

When the status code is 200, print the body. When there is an error, inspect the reason.

I get response from the server like so,

%HTTPoison.Response{body: "{\"USD\":10067.08}", headers: <<removed for readability>>, status_code: 200}

And the error of, (CaseClauseError) no case clause matching:

Why am I getting a "no clause" error when I'm getting a response with a body and status code of 200?

1 Answer 1

2

Issue is the ! after get

HTTPoison.get!(@api_url) will return %HTTPoison.Response{body: body, ...} or raise exception.

If you want {:ok, %HTTPoison.Response{body: body, ...} then use HTTPoison.get(@api_url) (without !) instead.

Either this:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.