Frederick John
Frederick John

Reputation: 527

Elixir "case clause error" while pattern matching HTTPoison response

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?

Upvotes: 0

Views: 4671

Answers (1)

Badu
Badu

Reputation: 1082

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

Upvotes: 2

Related Questions