简体   繁体   中英

(RuntimeError) expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection

In one of my controllers I've got the following code (excerpt):

case HTTPoison.get("https://*****.zendesk.com/api/v2/users/search.json?query=" <> clid, headers, [hackney: hackney]) do
  {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
    conn
    |> put_status(200)
    |> json(body)
  {:ok, %HTTPoison.Response{status_code: 404}} ->
    conn
    |> put_status(404)
    |> json(%{error_code: "404", reason_given: "Resource not found."})
  {:error, %HTTPoison.Error{reason: reason}} ->
    conn
    |> put_status(500)
    |> json(%{error_code: "500", reason_given: "None."})
end

When I run the code, it works fine, but Phoenix throws the runtime exception:

** (exit) an exception was raised:
    ** (RuntimeError) expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection
        (zentonies) web/controllers/page_controller.ex:1: Zentonies.PageController.phoenix_controller_pipeline/2
        (zentonies) lib/zentonies/endpoint.ex:1: Zentonies.Endpoint.instrument/4
        (zentonies) lib/phoenix/router.ex:261: Zentonies.Router.dispatch/2
        (zentonies) web/router.ex:1: Zentonies.Router.do_call/2
        (zentonies) lib/zentonies/endpoint.ex:1: Zentonies.Endpoint.phoenix_pipeline/1
        (zentonies) lib/plug/debugger.ex:93: Zentonies.Endpoint."call (overridable 3)"/2
        (zentonies) lib/zentonies/endpoint.ex:1: Zentonies.Endpoint.call/2
        (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
        (cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4

What am I doing wrong?

The stack trace is telling you that your controller action is not returning a Plug.Conn struct. In Elixir, the result of the very last expression of a function is returned. Look at the last line of your function and ensure it is returning the result of your case expression.

def(conn, params) do
  final_conn = 
    case HTTPoison.get("https://*****.zendesk.com/api/v2/users/search.json?query=" <> clid, headers, [hackney: hackney]) do
      {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
        conn
        |> put_status(200)
        |> json(body)
      {:ok, %HTTPoison.Response{status_code: 404}} ->
        conn
        |> put_status(404)
        |> json(%{error_code: "404", reason_given: "Resource not found."})
      {:error, %HTTPoison.Error{reason: reason}} ->
        conn
        |> put_status(500)
        |> json(%{error_code: "500", reason_given: "None."})
    end

  do_something_else(params)

  final_conn
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM