HTTPoison request CaseClauseError: no case clause matching JSON payload

158 views Asked by At

I hit the following CaseClauseError message attempting to make a request with HTTPoison:

20:13:10.697 [error] #PID<0.2628.0> running Api.Endpoint (connection #PID<0.2608.0>, stream id 2) terminated
Server: dev.company.com:80 (http)
Request: POST /an/endpoint
** (exit) an exception was raised:
    ** (CaseClauseError) no case clause matching: %{entity: %{some: "asdfasdf", parameters: "qwerqwer"}
        (hackney 1.18.1) /home/circleci/project/deps/hackney/src/hackney_request.erl:322: :hackney_request.handle_body/4
        (hackney 1.18.1) /home/circleci/project/deps/hackney/src/hackney_request.erl:87: :hackney_request.perform/2
        (hackney 1.18.1) /home/circleci/project/deps/hackney/src/hackney.erl:378: :hackney.send_request/2
        (httpoison 1.8.0) lib/httpoison/base.ex:846: HTTPoison.Base.request/6
        (web_api 0.1.0) lib/web_api/request.ex:84: WebApi.Request.entity/6
        (web_api 0.1.0) lib/web_api/request.ex:37: anonymous fn/5 in WebApi.Request.request/4
        (elixir 1.11.4) lib/enum.ex:1411: Enum."-map/2-lists^map/1-0-"/2
        (web_api 0.1.0) lib/web_api/request.ex:36: WebApi.Request.request/4

The code looks something like this:

body = %{entity: %{some: "asdfasdf", parameters: "qwerqwer"}}

HTTPoison.request(
   method,
   uri,
   body,
   headers,
   timeout: 30000,
   recv_timeout: 30000
)

And it's a bit unclear how to resolve it.

2

There are 2 answers

1
Hannele On BEST ANSWER

I just needed to make sure the request body was stringified first (using the Jason library here):

body = if is_nil(body), do: nil, else: Jason.encode!(body)

(Which does make sense, an HTTP client shouldn't be making choices about JSON encoding.)

0
wesfdev On

the first thing you should do is make sure that the request body is a string, to do this you can add the following dependency in your project:

{:jason, "~> 1.4"}

Download the dependency to your project:

mix deps.get

Then you can apply to your body the function that transforms a map into a string:

body = %{entity: %{some: "asdfasdf", parameters: "qwerqwer"}} |> Jason.encode!()

And that's it, I hope this answer has helped you.